请教个循环的小问题,一时卡住了。。。

minutes_seconds 2007-10-17 12:35:17
这段代码的if语句为什么当w<=1.12时可以打出stopstopstopstopstopstopstopstopstopstopstop,
而w>=1.14时确不可以啊?
觉得很奇怪。


#include <iostream>

using namespace std;

int main()
{
double w;

for ( w = 0.9; w <= 1.8; w = w + 0.02 )
{
cout << "w: " << w << endl;

if(w == 1.14)
{cout << "stopstopstopstopstopstopstopstopstopstopstop\n\n\n";}

else cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n";
}

getchar();

}
...全文
119 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
MPTD_Fire 2007-10-17
  • 打赏
  • 举报
回复
if(w - 1.14 < "你需要的精度")
{
cout...
}
else
{
cout...
}
MPTD_Fire 2007-10-17
  • 打赏
  • 举报
回复
1.为什么判断浮点数是否为0不能直接通过==比较。(详细说明)
浮点数是有精度的,不是一个确切数,float x = 0 时,x 的实际值可能为 0.0000001

2.详细阐述一下浮点数的其他比较: < > and ==
我一般用 (x-0)> 0.00...1 && (x - 0) < 0.00...1 来判断是否相等

MPTD_Fire 2007-10-17
  • 打赏
  • 举报
回复
黄瓜@YouCanDoIt 已经回答了,浮点数的比较不能用"=="的。把这个改了就没
问题了,比如用“>1.14”
minutes_seconds 2007-10-17
  • 打赏
  • 举报
回复
谢谢:)
我有个小小的疑问就是为什么w<=1.12时一切正常呢?
0黄瓜0 2007-10-17
  • 打赏
  • 举报
回复
有些数用二进制不能精确表示.
浮点数的比较不能用"=="的.

#define EPSILON 1.0E-7
if(w-1.14 < EPSILON && W-1.14 >-EPSILON)//这样就认为w和1.14相等.精度EPSILON可以按你的精度要求设置,但不能小于这两个数.
#define FLT_EPSILON 1.192092896e-07F /* smallest such that 1.0+FLT_EPSILON != 1.0 */
#define DBL_EPSILON 2.2204460492503131e-016 /* smallest such that 1.0+DBL_EPSILON != 1.0 */


下次发贴把代码规整下:

#include <iostream >

using namespace std;

int main()
{
double w;
for ( w = 0.9; w <= 1.8; w = w + 0.02 )
{
cout << "w: " << w << endl;
if(w == 1.14)
{
cout << "stopstopstopstopstopstopstopstopstopstopstop\n\n\n";}
else
cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n";
}
getchar();
}

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧