gpt4 book ai didi

C++,与 g++ 相等

转载 作者:太空宇宙 更新时间:2023-11-04 14:51:01 25 4
gpt4 key购买 nike

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

最佳答案

你的括号是错误的:

if ( (int) (10 * (  0.1 * index)  ==  (int)(10 * ( int ) ( 0.1 * index ) ) ) )

应该是:

if ( (int) (10 * (  0.1 * index) )  ==  (int)(10 * ( int ) ( 0.1 * index ) ) )

关于C++,与 g++ 相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5436039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com