0

While I was trying to solve the greedy less comfortable problem in pset1, I ran into a slight problem on the last loop in my program. Here is my code: (the reason why I have some random print statements inside the loops is because it helps me debug/locate where the problem is)

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

int main(void)
{

// declare variable amount
float amount;

// tracks the number of coins used
int coins_used = 0;

do
{
    amount = get_float("Change owed: ");
}
while (amount < 0);

// print statements used for debugging

while (amount >= 0.25)
{
    amount -= 0.25;
    printf("Decreased by 0.25\n");
    coins_used += 1;
    printf("Amount: %.2f\n", amount);
}

while (amount >= 0.10)
{
    amount -= 0.10;
    printf("Decreased by 0.10\n");
    coins_used += 1;
    printf("Amount: %.2f\n", amount);
}

while (amount >= 0.05)
{
    amount -= 0.05;
    printf("Decreased by 0.05\n");
    coins_used += 1;
    printf("Amount: %.2f\n", amount);
}

while (amount >= 0.01)
{
    amount -= 0.01;
    printf("Decreased by 0.01\n");
    coins_used += 1;
    printf("Amount: %.2f\n", amount);
}

printf("Final amount: %.2f\n", amount);
printf("Coins used: %i\n", coins_used);
}

As you can see, every time the program enters a loop, I make it print that it is decreasing the amount of change and adding 1 to the number of coins used just so I can pinpoint which loop was causing the problem. You might think the code is working well right now, and so did I a while ago, but here is the output I got when I tested my code with the input 0.41:

Change owed: 0.41
Decreased by 0.25
Amount: 0.16
Decreased by 0.10
Amount: 0.06
Decreased by 0.05
Amount: 0.01
Final amount: 0.01
Coins used: 3

As you can see, it says the final amount (change) is 0.01, so why did the program not enter the final loop? (The one that says while (amount >= 0.01)…)? I am confused, can someone tell me if they know what's going on?

1

You've run into float imprecision, which is the lesson of this Problem.

The spec and walkthrough advise you to convert the user's float amount into an integer representing the number of cents (and to beware of imprecision by rounding that value rather truncating).

Then, do all of your calculations with integers.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .