I just try to do the Pset1 cash task and have a little problem. Here is my code:

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

int main(void){

float numberOfCoins = 0;
int amQuarter;
int amDime;
int amNickel;
int amPenny;

printf("Change owed: ");
float change = get_float();

amQuarter = change / 0.25;
printf("Amount Quarter = %i\n", amQuarter);
change -= amQuarter * 0.25;
amDime = change / 0.1;
printf("AMount Dime = %i\n", amDime);
change -= amDime * 0.1;
amNickel = change / 0.05;
printf("Amount Nickel = %i\n", amNickel);
change -= amNickel * 0.05;
printf("Current change: %f \n", change);
amPenny = change / 0.01;
printf("Amount Penny = %i \n", amPenny);

numberOfCoins = amQuarter + amDime + amNickel + amPenny;

printf("Number of Coins = %f \n", numberOfCoins);

Thr printf in between were just for me, so I could check what happened. My problem is, that amPenny is always buggy.

For example, if I try it out with 0.41, in the end, we have amPenny = 0.01/0.01, and for some reason, that is 0. Or else 0.02/0.01 = 1.

Can someone tell me what is wrong and how to fix it?

1 Answer 1


Just a couple of things, you are assigning an operation between variables of type float to a variable of type int. When this is done the result is truncated, it is not rounded, hence the results you get. Second thing, the intention of the exercise is that you handle the rounding and imprecision implicit in the float type numbers, read about it, in the forum you can find a lot on the subject, finally if I remember correctly you should use the round () function with your change variable before doing operations with integers, you will surely need a new variable as indicated by the following code:

printf("Change owed: ");
float change = get_float();
int integerChange = round(change*100);

Surely you need the header file math.h

  • Alright, then I'll try it with round instead. Thanks :)
    – Robin
    Jan 28, 2018 at 21:34

You must log in to answer this question.

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