0

So I built this for CS50 (great course so far) but I'm not sure why the only error I've hit 1-100 cents is 53, which it gives as only 4 coins instead of the correct 5. I'm new to C and would love a second pair of eyes to see my mistake.

//Implement a program that calculates the minimum number of coins required to give a user change.

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


int main(void)
{

//get change owed, reject if negative
    float cash;
    printf("Change owed: ");

    do {
        cash= get_float();
    }
    while(cash<0);

//avoid imprecision by converting to cents
int cents = cash*100;

int count = 0;

//while(cash>1){
//    cash-1;
//    count++;
//}

while (cents>=25){
    count++;
    cents-=25;

}
while (cents>=10){
    count++;
    cents-=10;

}
while (cents>=5){
    count++;
    cents-=5;

}
while (cents>=1){
    count++;
    cents-=1;

}
printf("%i\n", count);

}
Mat
  • 202,337
  • 40
  • 393
  • 406
chauxvive
  • 238
  • 4
  • 16
  • 1
    stepping through with a debugger would be immensely helpful. – yano May 10 '18 at 18:13
  • Now is a good time to lean how to debug a program. What is the error specifically? – OldProgrammer May 10 '18 at 18:13
  • 1
    Print the value of cents before you start and after each while loop. That'll make it obvious. – Jens May 10 '18 at 18:14
  • Don't use floats to deal with money. You seem somewhat aware of this as you convert from float to int to just deal in cents, but even better would to be to start with an integral type in the first place. – Christian Gibbons May 10 '18 at 18:15
  • Do not use floats for anything you can count. – Yunnosch May 10 '18 at 18:15
  • The error is just that I'm getting back a wrong value- no error code. I have to use floats if I'm dealing with change- plus I'm following the CS50 tutorial which also does so. As for debugging- I'm a new coder, especially with C. Can you give me more information? – chauxvive May 10 '18 at 18:16
  • 2
    Hint: https://ideone.com/9MCWzw and http://en.cppreference.com/w/c/numeric/math/round – Bob__ May 10 '18 at 18:17
  • @chauxvive You do not, in fact, have to deal with floats. Just as you converted your `float cash` to `int cents`, you've shown you can represent the value with a non floating point. – Christian Gibbons May 10 '18 at 18:18
  • Bob that's so helpful, thank you- ! – chauxvive May 10 '18 at 18:21
  • 2
    `long cents = lround(cash*100.0);` – chux - Reinstate Monica May 10 '18 at 18:24
  • DO NOT USE FLOAT or double for currency. It is absolutely not necessary and will cause many bugs and unexpected behavior. – Lee Daniel Crocker May 10 '18 at 19:31
  • I'm actually pretty annoyed that CS50 wants us to use floats inappropriately like this. Seems like a mess for the first problem set. Thanks all, just trying to follow instructions on a new language. – chauxvive May 11 '18 at 03:08

0 Answers0