首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

这个如何理解

2012-10-26 
这个怎么理解#includeiostreamint main(){using namespace stdfloat hats50.25,heads11.17cout.setf

这个怎么理解
#include<iostream>
int main()
{
using namespace std;
float hats=50.25,heads=11.17;
cout.setf(ios_base::fixed,ios_base::floatfield);
cout<<"+="<<hats+heads<<endl;
cout<<"-="<<hats-heads<<endl;
  cout<<"*="<<hats*heads<<endl;
cout<<"/="<<hats/heads<<endl;
return 0;
}
结果:
+=61.419998
-=39.080002
*=561.292480
/=4.498657
Press any key to continue

问:
为什么加的结果不是61.42?
减的结果后面怎么多了个2?

[解决办法]
float不精确吧 当float=1;
输出来就可能是大于1或小于1的小数了
[解决办法]

探讨
#include<iostream>
int main()
{
using namespace std;
float hats=50.25,heads=11.17;
cout.setf(ios_base::fixed,ios_base::floatfield);
cout<<"+="<<hats+heads<<endl;
cout<<"-="<<hats-heads<<endl;
……

[解决办法]
浮点运算只能表示一个区间,这个也是为什么浮点运算为什么不能直接横等(==)比较,虽然可以,但是基本上会悲剧,一般float精度范围,小数点6-7位吧,这个可以看谭浩强的C语言书,自己看浮点那一章,你就懂了。

热点排行