Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

c - 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          
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...