0

guys

My code functioned correctly in all other numbers I input, except when I input 4.2. It should just used up 18 coins, which is 16 quarters and 2 dimes, but instead it used:

25(quarter): 16 10 (dime): 1
5 (nickel): 1
1 (penny): 4
using 22 coins

I did alter the input from float to integer, but it decreased 1 itself automatically when transferring into an integer. What am I missing?

BTW I altered my code a bit to see how it allocate the money into different type of coins. My code:

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


int main(void)
{
    printf("Enter how much you are owed:");
    float change = get_float();

    while(change < 0)
    {
        printf("Try again:");
        change = get_float();
    }

    printf("This is the change orginally: %f\n", change);
    int changes;
    changes = change*100;
    printf("This is the changes in float: %d\n", changes);



    int num_25 = 0;
    int num_10 = 0;
    int num_5 = 0;
    int num_1 = 0;

    while(changes >= 25)
    {
        do
        {
            changes = changes - 25;
            num_25 = num_25 + 1;
        }
        while(changes >= 25);
    }

    while(changes >= 10)
    {
        do
        {
            changes = changes - 10;
            num_10 = num_10 + 1;
        }
        while(changes >= 10);
    }
    while(changes >= 5)
    {
        do
        {
            changes = changes - 5;
            num_5 = num_5 + 1;
        }
        while(changes >= 5);
    }

    while(changes >= 1)
    {
        do
        {
            changes = changes - 1;
            num_1 = num_1 + 1;
        }
        while(changes >= 1);
    }

int num = num_25 + num_10 + num_5 + num_1;

    printf("25 cent: %i\n", num_25);
    printf("10 cent: %i\n", num_10);
    printf("5 cent: %i\n", num_5);
    printf("1 cent: %i\n", num_1);
    printf("Get %i coins", num);
}

and this is the output when entering change =4.2 enter image description here

1 Answer 1

0

Ah, the $4.20 test has caught another one!

This time, I think I'll just drop a couple hints.

Hint #1: Why is change = 4.20 but changes = 4.19?

Hint #2: When a float is assigned to an int, the fractional part of the float is truncated, not rounded.

BTW, how many coins in $4.19? ;-)

See if that gets you to a solution. ;-)

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

1
  • Solve it! Thanks :) Sep 30, 2017 at 11:32

You must log in to answer this question.

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