【发布时间】:2021-01-21 07:47:17
【问题描述】:
#include <stdio.h>
#include <string.h>
int main() {
int start, end, i, sum = 0, temp, x, y, z;
puts("Please enter the starting number: ");
scanf("%d", &start);
temp = start;
x = start; y = start + 1;
puts("Please enter the last number till you want to add: ");
scanf("%d", &end);
for (i = start; i < end; i++) {
z = x + y;
x = z;
y = y + 1;
}
printf("The sum of the numbers starting from %d to %d is %d", temp, end, z);
}
谁能找出这段代码有什么问题?
对于较少的数字它可以正常工作,但是当我分配像 1 到 1000000 这样的大数字时,它不起作用,即它返回奇怪的值。
案例 1:
Please enter the starting number:
1
Please enter the last number till you want to add:
100
The sum of the numbers starting from 1 to 100 is 5050
但在这种情况下-
案例 2:
Please enter the starting number:
1
Please enter the last number till you want to add:
1000000
The sum of the numbers starting from 1 to 1000000 is 1784293664
这种情况有什么问题?提前致谢。
【问题讨论】:
-
我觉得这个值对于
int来说太长了,可能会溢出,尝试切换到unsigned long long -
注意:有符号整数溢出是未定义的行为。
-
@DavidRanieri 我很确定是UB,毕竟是规范中提到的直接例子。
-
@DavidRanieri Unsigned 整数溢出是在 C99 和 C89 中定义的行为。
-
@DavidRanieri 重申:无符号溢出在 C17、C11、C99、94、C89 中定义。不是implementation defined up to version C11。 C89 有:“涉及无符号操作数的计算永远不会溢出。因为不能由得到的无符号整数类型表示的结果以比得到的无符号整数类型可以表示的最大值大一的数字为模减少” C89 6.1.2.5.