0

Hello everybody! I have a little problem in a piece of code that seems quite simple. This piece of code reads float numbers till the user hits the number -999.9. When he/she does then the program ends. So i write

float n;
           scanf("%d", &n);
            while (n != -999.9) {
                i++;
                scanf("%d", &n);
                    }

The problem is that when i hit simply -999 the piece of code works. But when i hit -999.9 then it doesn't work. I think it's the decimal part that causes the problem but i can't imagine why...Any idea will be appreciated. Thank you in advance for spending your time with me.

3
Contributors
4
Replies
6
Views
7 Years
Discussion Span
Last Post by Tellalca
0

floating point precision can screw up your condition. What you perceive as an exact -999.9 is not, since it can be -999.9000001.
Moral of the story: Do not use floating point for loops to prevent broken code and ensure portability.

Edited by Aia: n/a

1

You should avoid using float values in conditions.

The problem with your code is "scanf("%d", &n );". You are getting input in the form of integer so you are ignoring the fraction part of the input.

You should use "scanf("%f", &n);" to get a floating number.

0

No that's not my error. I use "%f" in my program. I'm sorry for my mistake in the post. I think the first answer covered me. Thank you all for replying instantly..

0

Ofcourse I cannot know what you used in the program, I look what you post here.

Your mistake is using floating numbers in a desicion statement.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.