WWoPPoWW
WWoPPoWW

Reputation: 61

scanf in while loop > 1

#include <stdio.h>
/**********************
Read in numbers and add only the positive one.
Quit when input is 0.
***********************/
int main()
{
    float num,sum = 0.0 ;

    while(scanf("%f",&num) > 0)
    {
        if (num == 0)
            break;

        else if (num > 0)
            sum += num;

    }
    printf("sum = %f\n",sum);

    return 0;

}

I'm confused as to why this code work normally until I changed this line while(scanf("%f",&num) > 0 ) to while(scanf("%f",&num) > 1 ) or 2,3,4,5,...... ( it's not working ) but when I changed it to while(scanf("%f",&num) > -1 ) or -2,-3,-4,-5,.... it works perfectly

Upvotes: 0

Views: 188

Answers (1)

Helix112
Helix112

Reputation: 306

Your check inside the while loop doesn't detect that value which you've provided (n). It reads a float and puts it inside n. Then the return value of scanf is not the value it reads from user input but the number of values read, which in your case are 1. That's why when you change it to 2 it won't work.

Upvotes: 1

Related Questions