新手,关于float类型的疑问。
#include <iostream>
using namespace std;
int main()
{
float hats,heads;
cout.setf(ios_base::fixed,ios_base::floatfield);
cout<<"Enter a number: ";
cin>>hats;
cout<<"Enter another number: ";
cin>>heads;
cout<<"hats= "<<hats<<"; heads= "<<heads<<endl;
cout<<"hats+heads= "<<hats+heads<<endl;
cout<<"hats-heads= "<<hats-heads<<endl;
cout<<"hats*heads= "<<hats*heads<<endl;
cout<<"hats/heads= "<<hats/heads<<endl;
return 0;
}
在这段程序中,我输入50.25和11.17。为何hats+heads=61.419998,而不是61.420000呢?
[解决办法]
cout<< setprecision(2) <<"hats+heads= "<<hats+heads<<endl;
用10进制小数不能精确表示某些三进制小数0.1(3)=0.33333333333……(10)
同理,用二进制小数也不能精确表示某些10进制小数。
[解决办法]
float
大多数电脑都是用二进制来表示浮点和整数的,
在十进制里,0.1是个简单、精确的小数,但是用二进制表示起来确实一个循环小数0.00011001100……,
所以在对一些二进制无法精确的表示的小数进行赋值或读入,再输出的话,
也就是从十进制转为二进制转为十进制,得到的数值是不一致的,
这是用于编译器二进制/十进制转换例程的精度引起的!