NotLanden NotLanden - 3 months ago 7
C Question

In C, I have a floating point variable decreasing by an incorrect amount

I'm writing a program in C to calculate change owed. You're supposed to enter in a value and get a message back displaying something like: "Your change is: x quarters, x dimes..."

The system works through 4 "for" loops. Each checks if a variable, x, is less than the value of the user inputted value (money). If so, then x is increased by some coin value (i.e. 0.25), a variable that counts a specific coin is increased, and the value inputted by the user is decreased by some coin value.

The problem is that the value inputted by the user (stored in a float called money) is decreased by an incorrect amount. 1 - 0.25 should be 0.75, right? Yet, for some reason, my program changes the value of 'money' to 0.500000.

Here's the code:

float money = 0.00;
int q = 0;
int d = 0;
int n = 0;
int p = 0;
float x = 0.00;

printf("Enter amount: ");
money = GetFloat(); // This function is part of a library called cs50.h

for (x = 0.00; x < money; (x = x + 0.25)) {
q++;
money = (money - 0.25); // This, and everything else like this, is the problem
}

for (x = 0; x < money; (x = x + 0.10)) {
d++;
money = (money - 0.10);
}

for (x = 0; x < money; (x = x + 0.05)) {
n++;
money = (money - 0.05);
}

for (x = 0; x < money; (x = x + 0.01)) {
p++;
money = (money - 0.01);
}

printf("Your change is: %i quarters, %i dimes, %i nickles, and %i pennies.\n", q, d, n, p);

Answer

didnt really read your story but 0.500 is exactly what your for loop produce

for (x = 0.00; x < money; (x = x + 0.25)) {
    q++;
    money = (money - 0.25); // This, and everything else like this, is the     problem
}

assume money is 1: after 1st iteration: x becomes to 0.25 and money becomes 0.75 then you have 2nd iteration: x becomes to 0.5 and money becomes 0.5 after 2nd iteration, your loop is over. therefore money = 0.5f

and all your loop has exactly the same problem. Remember that your loop only stops when the condition x < money does not hold.

Comments