为什么 gcc 编译器输出 pow(10,2) 为 99 而不是 100?

2021-12-18 00:00:00 gcc c++
#include <iostream.h>
#include <math.h>
int main()
{
    int j=2;
    int output;
    output=pow(10,j);
    cout<<output;
    return 0;
}

我将上述代码写入 gcc 12 编译器并得到了输出 99 而不是 100.在各种站点上搜索时我没有得到正确的原因.编译器有问题吗?

I wrote above code to gcc 12 compiler and got the output 99 instead 100. I don't get the valid reason while searching on various sites. Is there any compiler problem?

推荐答案

因为整数截断.pow() 返回一个浮点值,由于浮点运算,大概是~99.999...;然而,由于整数截断,即使 99.999... 也会被截断为 99.

Because of integer truncation. pow() returns a floating point value, and due to floating point arithmetic, it is probably ~ 99.999...; however, due to integer truncation, even 99.999... gets truncated down to 99.

相关文章