为什么我的代码会产生无限循环? [英] Why do I get an endless loop from my code?
问题描述
#include <stdio.h>
int main() {
int num;
int square;
int sum;
while (num) {
if (num > 0) {
scanf("%d", &num);
square = num * num;
sum = square + sum;
printf("%d \n", sum);
}
}
return 0;
我试图生成正数的平方和,当输入第一个负数时,循环结束.结果需要左对齐10个空格.
该代码具有未定义的行为:首次测试num
的值时,该代码未初始化.如果偶然碰巧它不是负数,则扫描一个新值,然后将其平方添加到未初始化的变量sum
中,从而产生更多未定义行为,如果该值输入为负数,则下一个测试失败,循环将永远重复.>
使用%-10d
转换格式可获得10个空格宽度的左对齐.
这是更正的版本:
#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\n", sum);
}
return 0;
}
如果希望数字以10个空格的宽度右对齐,以便所有输出值正确对齐,请改用%10d
格式.
如果输入大量或太多项目,最终将超出类型int
的范围.您可以通过将变量square
和sum
设置为long long int
或什至由PeterJ unsigned long long int
注释来扩大它们的范围,并允许计算更大的值:
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\n", sum);
}
return 0;
}
请注意,(long long)num * num
将转换为具有至少等于正值范围的范围的unsigned long long
.
#include <stdio.h>
int main() {
int num;
int square;
int sum;
while (num) {
if (num > 0) {
scanf("%d", &num);
square = num * num;
sum = square + sum;
printf("%d \n", sum);
}
}
return 0;
I'm trying to produce the sum of squares for positive numbers, and when the first negative number is inputted, the loop ends. Result needs to be left justified by 10 spaces.
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\n", 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\n", 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.
这篇关于为什么我的代码会产生无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!