简体   繁体   中英

hi there, a question about break statement in c programming

I wrote this loop to add numbers,and the break to get out of the loop if the number entered is less than zero, and in last print the calculated numbers without adding the negative number. but the problem is even I wrote the break statement before the addition when I enter 15 and 15 and -2 the output is 28 rather than 30 I found out how to fix that, what I want to know is why and thank you.

#include<stdio.h>

void main()
{
    int j =1, num =0, rslt =0;
    while(1) {
        if (num<0) break;
        printf("enter a number : ");
        scanf("%d", &num);
        rslt = rslt+num;
    }
    printf("the resluts are %d\n", rslt);

Currently, you are effectively testing the input of the previous iteration, after already adding it to your result. Instead, check the number immediately after the user enters it, before you perform any calculations.

#include <stdio.h>

int main(void)
{
    int num = 0, rslt = 0;

    while (1) {
        printf("enter a number : ");
        scanf("%d", &num);
        
        if (num < 0)
            break;
                               
        rslt += num;           
    }                          
                              
    printf("the results are %d\n", rslt);
}

You might also want to check that scanf returns the number of successful conversions you were expecting (in this case one), to handle the event where the user enters invalid input.

if (1 != scanf("%d", &num))
    break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM