Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this loop not break immediately when the user inputs -0.1

I was reviewing some exercises I did for my algorithms class when I stumbled onto this piece of code and it didn't work as I thought it would.

So the exercise is the following: write a program that asks for a positive integer then print its double unless the number is negative.

So here is the code:

int main(void) {
    int n = 1;

    while (n >= 0) {
        printf("Veuillez introduire un nombre entier positif: ");

        if (!(scanf("%i", &n)) || n < 0) 
            break;

        printf("Le double de %i est de: %i\n", n, (2 * n));
    } 
}

Simple enough.

The thing is that the program stops immediately if I try to input a character, a negative number,… as expected but if I input "-0.1" it first prints the double of 0 which is 0 then runs the loop again up to the if statement.

If I just input 0 or even -0 it doesn't do that it keeps running (which it should since 0 isn't a negative number).

Here is the output:

Veuillez introduire un nombre entier positif: -0  
Le double de 0 est de: 0  
Veuillez introduire un nombre entier positif: 1  
Le double de 1 est de: 2  
Veuillez introduire un nombre entier positif: -0.1  
Le double de 0 est de: 0  
Veuillez introduire un nombre entier positif: 

It stops there.

I just can't wrap my head around this. Sorry if this is trivial.

Thank you for your time.

NB: This is my first post, I haven't found the answer here, so if you found it or if you have feedback feel free to post it, it'd be appreciated.

EDIT: swapped screenshot of output with text

like image 752
viraltaco_ Avatar asked Mar 12 '26 09:03

viraltaco_


1 Answers

With the format %i, scanf() reads an integer. If you type -0.1, the integer is -0. This isn't less than 0, so the loop continues.

The next time through the loop, it tries to read an integer from .1. Since this isn't an integer, the scan fails and scanf() returns 0. This causes !scanf("%i", &n) to be true, so break; is executed and the loop stops.

like image 80
Barmar Avatar answered Mar 13 '26 22:03

Barmar