0

I've been trying to make the greedy problem set, but something isn't working. The program works fine with numbers like 1,2,3,4... But it fails when I try to use a decimal number. This is my code:

enter code here#include 
<cs50.h>
#include <stdio.h>
#include <math.h>

int main(void)
{
// Variables to store counting data
float coin_count = 0;
float owed;

// Prompts user for a valid float
do
{
    printf("O hai! How much change is owed?\n");
    owed = roundf(GetFloat());
}
while (owed <= 0);

// Checks what which coins to use
for (float quarter = .25; owed >= quarter; coin_count++)
{
    owed = owed - quarter;
}

for (float dime = .10; owed >= dime; coin_count++)
{
    owed = owed - dime;
}

for (float nickel = .05; owed >= nickel; coin_count++)
{
    owed = owed - nickel;
}

for (float penny = .01; owed >= penny; coin_count++)
{
    owed = owed - penny;
}

//coin_count = round(coin_count);
printf("%.50f\n", coin_count);
}

I tried multiplying and dividing by 100 but that didn't work for me :/ Could someone help me?

3 Answers 3

1

The problem is at the root of the purpose of this assignment. Floating point numbers are not always stored exactly accurately in a computer. For instance, if you check (with a high-resolution printf statement), you'd see that 4.2 is stored in a computer as something more like 4.1999999997875 (the actual number is different, but you get the idea.) Because of the way the computer outputs the number by default, it might print as 4.2, but when you increase the number of digits printed, the computer stops rounding the least significant digit and you start to see the error.

The purpose of this pset is to understand this behavior, and to figure out how to deal with it. The problem that you are running into is something like this: say that you start with $4.20. The various coins are removed and counted as you go, but eventually you get down to $0.10. Actually, you're at something like $0.0999999879. Since the code tests for owed < .10 it misses that one more dime would do the job.

If this answers your question, please click the check mark and accept. Let's keep up on forum maintenance. ;-)

0

I reviewed the man page for roundf, and it says "These functions round x to the nearest integer,". Probably owed = roundf(GetFloat()); is dropping your decimal places.

0

I suggest multiplying 'owed' by 100 then rounding. By doing this you will only be dealing with the number of cents, an integer, instead of dollars and cents, a float. If you do this you will also have to change the values of the coins from decimals to integers.

You must log in to answer this question.

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