【发布时间】:2020-12-07 11:59:23
【问题描述】:
我的代码:
#include <stdio.h>
#include <math.h>
int main (void)
{
int n = 0;
int sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
for (int power = 1; power <= n; power++)
{
printf("%d %s ", (int)pow(10, power) - 1, power == n ? "=" : "+");
sum += (int)pow(10, power) - 1;
}
printf ("%d", sum);
return 0;
}
使用 gcc 在 Vs 代码中输出:
Enter a number: 5
9 + 98 + 999 + 9998 + 99999 = 111103
在线编译器的输出:
Enter a number: 5
9 + 99 + 999 + 9999 + 99999 = 111105
我的问题:为什么?发生这种情况了吗?
【问题讨论】:
-
The classic answer 。此外,使用相同的编译器和不同的优化设置,您可能会得到不同的答案。
-
对于这些类型的问题,当涉及到编译器版本时,请尽可能具体。 “在线编译器”不是一个很好的描述,“带有 gcc 的 VS 代码”也不够。什么版本?有哪些选择?
-
几个问题:首先,代码总是向下舍入,如果 pow 结果略低于封闭整数,这可能是一个问题。其次,它不检查输入。它很容易溢出。第三:总和累加舍入误差。
-
我现在用 gcc 9.3、onlinegdb.com/online_c++_compiler 和 Visual c 版本 19.16.27043 测试了上面的代码。他们都没有表现出上述行为。您是否使用了一些过时的编译器版本?您使用了哪个运行时/sdk 版本(如果您使用的是 vc)?