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";
}
}
Run Code Online (Sandbox Code Playgroud)
使用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
Run Code Online (Sandbox Code Playgroud)
DHa*_*all 11
你的括号错了:
if ( (int) (10 * ( 0.1 * index) == (int)(10 * ( int ) ( 0.1 * index ) ) ) )
Run Code Online (Sandbox Code Playgroud)
应该:
if ( (int) (10 * ( 0.1 * index) ) == (int)(10 * ( int ) ( 0.1 * index ) ) )
Run Code Online (Sandbox Code Playgroud)