Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

#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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...