0

Im new here my name is Brian Upward. Im having a bit of trouble with the greedy problem. This is returning outrageous numbers in the 30 thousands and I'm not sure why. I also tried a similar approach using a do/while loop and I received the same issues. I am sensing that the issue lies within the decimal but I'm not sure how else to write it. Any help would be greatly appreciated. Thanks, Brian

edit: Also I tried using (1/4) instead of 0.25 which didnt seem to work.

#include <cs50.h>

include

include

int main(void) { float change; int quarter, dime, nickel, penny;

printf("How much change is owed?\n");
change = GetFloat();
float roundf(float change);

while(change >= 0.25)
{
    quarter = quarter + 1;
    change = change - 0.25;
}

while(change >= 0.1)
{
    dime = dime + 1;
    change = change - 0.1;
}

while(change >= 0.05)
{
    nickel = nickel + 1;
    change = change - 0.05;
}

while(change >= 0.01)
{
    penny = penny + 1;
    change = change - 0.01;
}

printf("I owe you %i Quarters ", quarter);
printf("%i Dimes ", dime);
printf("%i Nickels ", nickel);
printf("and %i pennies. Thank you, have a nice day!", penny);

}

1

Your code looks good, I suggest a few changes:

  1. PSET specs say you should only accept a non-negative value, and keep on re-prompting user until such a value is provided. Your code doesn't do this and will fail check50.
  2. The reason why you are getting large numbers is because you did not initialize your variables. You should set them =0 when declaring them. Otherwise they contain garbage values left over from whatever was stored in that particular space in memory.
  3. You are better off expressing everything in cents, so multiply change by 100 right after you accept user input. Be sure to change the figures in your while loops to cents as well. Finally, it's "round", not "roundf".
| improve this answer | |
  • Thank you very much for the the response. I added in the re-prompt. I set all my integers to 0 (int quarter, dime, nickel, penny = 0;) I multiplied everything by 100. Im having a bunch of errors come up when I remove the 'f' beside round. I ran the script keeping it in and I am still getting massive numbers. – Brian Upward Jan 25 '16 at 3:34
  • Your second point seemed to be the solution. My residing issue was that I was unable to declare all the integers on the same line I just had to type them out separately. Also roundf did work. Thanks alot! – Brian Upward Jan 25 '16 at 3:48
  • My mistake, you're right of course, it's a float so roundf will work. You'd need to include <math.h> header though, which you didn't do in your code above. – ronga Jan 26 '16 at 1:11
  • Ohhh right. I think it was cut off for some reason, I had cs50, stdio and math. Thanks again though! – Brian Upward Jan 27 '16 at 23:14

You must log in to answer this question.

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