C语言 编制发行说明书[副本]

dz6r00yl  于 2024-01-06  发布在  其他
关注(0)|答案(1)|浏览(127)

此问题在此处已有答案

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我如何解决这个问题?*
我想我解释了一切

eaf3rand

eaf3rand1#

j = pow(i, 2);更改为j = i*i;以仅使用整数运算。
pow是一个浮点函数。当一个精确的结果是可表示的时,它应该产生一个精确的结果,但是低质量的实现产生近似值,例如pow(10, 2)的99.99999999999999857891452847979962825775146484375。
double值99.999999999999857891452847979962825775146484375转换为int以分配给j时,它被截断为99。
当你计算i*i时,乘积将用整数运算来计算,不会有近似值。(然而,当值超过类型所能表示的界限时,整数运算将溢出。)

相关问题