Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

While doing my homework I noticed something really strange that I just can't figure out why.

int x = 5;
cout << pow(x, 2);

The result is 25. That's fine. But if I write the same program like this:

int x = 5;
int y = pow(x, 2);
cout << y;

The result is 24!

When x is 2, 3, 4, 6, 7, 8 no problem, but with 5, 10, 11, 13 etc. result is 1 lower than it should be.

Same thing with if().

for (int x = 1; x <= 20 ; x++) {
    if (x * x == pow(x, 2)) 
    cout << x << endl;
}

It prints out numbers 1, 2, 3, 4, 6, 8, 12, 16.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
269 views
Welcome To Ask or Share your Answers For Others

1 Answer

std::pow() returns a floating point number. If the result is for instance 24.99999999 and you cast it to int, it will be cut off to 24.

And that is what you do in the 2nd code example.
cout does not convert to int and outputs the correct result in the 1st code example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...