Dave Helmig Dave Helmig - 2 months ago 4x
C Question

Small bug in my short C code. Why?

I can't figure out why this works for 90% of the inputs, but not the others. It is meant to tell you how many coins you would get back in change. Most test amounts work fine, but if you enter 4.20 (or $4.20), it returns 23 coins... it should be 18 coins (16 quarters and 2 nickels). Where is the bug? Here is my code:

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

int main(void){

float change = 0.00;

printf("How much change is owed? ");
change = GetFloat();

float quarters = change/.25;
change-= (int)quarters*.25;

float dimes = change/.10;
change-= (int)dimes*.10;

float nickels = change/.05;
change-= (int)nickels*.05;

float pennies = (change+.005)/.01;

int total = (int)quarters+(int)dimes+(int)nickels+(int)pennies;

printf("%d\n", total);

return 0;


Throw out the floating-point calculations. this is all based on hundredths at best, so just use integer division/modulo. Never rely on perfect accuracy in floating point numbers.

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

int main(void){

    float fchange = 0.00;
    int change = 0;

    printf("How much change is owed? ");
    fchange = GetFloat();

    change = (int)roundf(fchange*100.0);

    int quarters = change/25;
    change = change % 25;

    int dimes = change/10;
    change = change % 10;

    int nickels = change/5;
    change = change % 5;

    printf("%d quarters, %d dimes, %d nickels, %d pennies\n", quarters, dimes, nickels, change);

    return 0;