奇怪的战俘(x,y);行为 [英] Strange pow(x, y); behaviour

查看:63
本文介绍了奇怪的战俘(x,y);行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在做作业的时候,我发现一些非常奇怪的东西,我什至不知道为什么.

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

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

结果是25.很好.但是,如果我像这样编写相同的程序:

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;

结果是24!

当x为2、3、4、6、7、8时没问题,但是当有5、10、11、13等时,结果比应有的值低1.

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.

与if()相同.

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

它打印出数字1、2、3、4、6、8、12、16.

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

推荐答案

<代码> std :: pow() 返回浮点数.如果结果是例如 24.99999999 ,并且将其强制转换为 int ,它将被剪切为 24 .

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.

这就是您在第二个代码示例中所做的.
cout 不会转换为 int ,并在第一个代码示例中输出正确的结果.

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.

这篇关于奇怪的战俘(x,y);行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆