C++,与 g++ 相等;
Why this condition is never true ? Both parts of the equation are integers, so there must be equality for index = 0, 10, 20, 30, 40. I am compiling this code using g++.
for(int index = 0; index < 50; index++){
if ( (int) (10 * ( 0.1 * index) == (int)(10 * ( int ) ( 0.1 * index ) ) ) )
{
std::cout << "equal";
}
}
使用 MSVS 2010 编译器,这些问题不会发生...
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 10
11 10
12 10
13 10
14 10
15 10
16 10
17 10
18 10
19 10
20 20
21 20
22 20
23 20
24 20
25 20
26 20
27 20
28 20
29 20
30 30
31 30
32 30
33 30
34 30
35 30
36 30
37 30
38 30
39 30
40 40
41 40
42 40
40 40
44 40
45 40
46 40
47 40
48 40
49 40
Why this condition is never true ? Both parts of the equation are integers, so there must be equality for index = 0, 10, 20, 30, 40. I am compiling this code using g++.
for(int index = 0; index < 50; index++){
if ( (int) (10 * ( 0.1 * index) == (int)(10 * ( int ) ( 0.1 * index ) ) ) )
{
std::cout << "equal";
}
}
With MSVS 2010 compiler these problems do not occur...
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 10
11 10
12 10
13 10
14 10
15 10
16 10
17 10
18 10
19 10
20 20
21 20
22 20
23 20
24 20
25 20
26 20
27 20
28 20
29 20
30 30
31 30
32 30
33 30
34 30
35 30
36 30
37 30
38 30
39 30
40 40
41 40
42 40
40 40
44 40
45 40
46 40
47 40
48 40
49 40
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你的括号是错误的:
应该是:
Your parentheses are wrong:
Should be:
您正在比较两个浮点数 - 0.1*index。
当各个组件不相等时,您是否尝试过打印它们?我怀疑你会发现等式中的某个地方,结果会有所不同。
You're comparing two floating point numbers - 0.1*index.
Have you tried printing out the individual components when they're not equal? I suspect you'll find that somewhere in the equation, the results vary.
这是因为在第二部分中你有 ( int ) ( 0.1 * index )。因此 (int) (0.1 * 5) 会四舍五入为 0。
It's because in the second part you have ( int ) ( 0.1 * index ). So (int) (0.1 * 5) becomes rounded to 0.
两边不都是整数:
是一个双精度数,并且使用
0.1
,正如您可能知道的那样,它不能以 IEEE754 格式精确表示(唯一可以精确表示的值是 1/( 的整数倍) 2^n) 其中 n>=0)。为了与人类通常使用的基数 10 进行类比,计算机看到的0.1
或多或少就像您看到的0.3333333333333...
(而且您没有无限的纸可以写下来)所有这些三)。您应该遵循 ybungalobil 的建议,顺便说一句,在我看来,使用基于整数算术和模运算符的不同方法来解决您的问题会容易得多。
似乎是您正在寻找的测试。
The two sides are not both integers:
is a double, and uses
0.1
that as you probably know cannot be represented exactly in IEEE754 format (the only values that can be represented exactly are integral multiples of 1/(2^n) with n>=0). To make a parallel with base 10 normally used by humans a computer sees0.1
more or less like you see0.3333333333333...
(and you dont' have infinte paper to write down all those threes).You should follow the advice of ybungalobill, and by the way to me seems that your problem would be a lot easier to solve using a different approach based on integer arithmetic and the modulo operator.
seems to be the test you are looking for.
尝试
try