The code has undefined behavior: the first time you test the value of num
, it is uninitialized. If by chance it happens to not be negative, you scan a new value and add its square to uninitialized variable sum
, producing more undefined behavior, it the value input was negative, the next test fails and the loop repeats forever.
Left justifying in a 10 space width is obtained with the %-10d
conversion format.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int num, square, sum = 0;
while (scanf("%d", &num) == 1 && num != 0) {
square = num * num;
sum = square + sum;
printf("%-10d
", sum);
}
return 0;
}
If you want the number to be right justified in a 10 space width so all output values align properly, use the %10d
format instead.
If you input large numbers or too many items, you will eventually exceed the range of type int
. You can try and increase the range of variables square
and sum
by making them long long int
or even as commented by PeterJ unsigned long long int
, and allow for larger values to be computed:
int main(void) {
int num;
unsigned long long square, sum = 0;
while (scanf("%d", &num) == 1 && num != 0) {
square = (long long)num * num;
sum = square + sum;
printf("%21llu
", sum);
}
return 0;
}
Note that (long long)num * num
will be converted to unsigned long long
that has a range at least as large in the positive values.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…