Éanan Halferty Éanan Halferty - 1 year ago 83
C Question

Why is this do while loop not working properly?

I want it to ask user for a float input to assign to money such as a dollar. The smallest unit would be a cent or 0.01 so I want it to reprompt the user for input every time he enters a negative value or zero. The while condition seems fine. What is wrong with it?

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)
float amount = 0;
printf("How much change to be returned?\n");
amount = GetFloat();
while(amount < 0.01);

Sample run:

jharvard@appliance (~/Dropbox/pset1): ./greedy
How much change to be returned?
How much change to be returned?

As you can see when I enter 1 cent it repeats the loop. If I enter 0.02 it works but I want to know why it's doing this.

Answer Source

0.01 Cannot be represented exactly in a float variable, therefore I conclude that in your case the input of 0.01 is converted to a float value bigger than the 0.01 constant and consequently the loop is not terminating for input of 0.01.

To fix this you can switch to a full blown currency or fixed point datatype or more simply change the program to work with cents instead of dollars, thereby avoiding fractional values and especially those of them that cannot be represented exactly. Another often used technique from Kirhog's answer is to use an Epsilon in you comparisons, e.g.:

double EPSILON = 0.005;
while(amount < 0.01+EPSILON);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download