此问题在此处已有答案:
Strange behaviour of the pow function(5个答案)
17天前关闭.
#include<stdio.h>
#include<math.h>
int main(){
int i;
int j;
for (i = 0; i <= 10; i++)
{
j = pow(i, 2);
printf("the square of %d is %d\n", i, j);
}
return 0;
}
- 当我在vscode中运行这个程序时,它在终端中给我这个结果:*
the square of 0 is 0
the square of 1 is 1
the square of 2 is 4
the square of 3 is 9
the square of 4 is 16
the square of 5 is 24
the square of 6 is 36
the square of 7 is 49
the square of 8 is 64
the square of 9 is 81
the square of 10 is 99
型
- 现在注意到5和10的平方是不正确的。当我问gpt它说pow应该变成double而不是int,当我这样做时,程序运行完美,这里的问题是第一个程序deos没有生成错误,所以问题是在编译器本身,事实上,当我在在线c编译器中运行程序时,它给我这些结果:*
the square of 0 is 0
the square of 1 is 1
the square of 2 is 4
the square of 3 is 9
the square of 4 is 16
the square of 5 is 25
the square of 6 is 36
the square of 7 is 49
the square of 8 is 64
the square of 9 is 81
the square of 10 is 100
型
- 现在注意到值是正确的
在summery我如何解决这个问题?*
我想我解释了一切
1条答案
按热度按时间eaf3rand1#
将
j = pow(i, 2);
更改为j = i*i;
以仅使用整数运算。pow
是一个浮点函数。当一个精确的结果是可表示的时,它应该产生一个精确的结果,但是低质量的实现产生近似值,例如pow(10, 2)
的99.99999999999999857891452847979962825775146484375。当
double
值99.999999999999857891452847979962825775146484375转换为int
以分配给j
时,它被截断为99。当你计算
i*i
时,乘积将用整数运算来计算,不会有近似值。(然而,当值超过类型所能表示的界限时,整数运算将溢出。)