-1

After getting help here with pset 1 and making through it , I now fumbled at pset1-Greedy.

According to the CS50 check my code for Greedy gets this result:

:) greedy.c exists

:) greedy.c compiles

:( input of 0.41 yields output of 4
 \ expected output, but not "0\n"

:( input of 0.01 yields output of 1
\ expected output, but not "0\n"

:( input of 0.15 yields output of 2
\ expected output, but not "0\n"

:( input of 1.6 yields output of 7
\ expected output, but not "8\n"

:) input of 23 yields output of 92

:( input of 4.2 yields output of 18
\ expected output, but not "16\n"

:) rejects a negative input like -.1

:) rejects a non-numeric input of "foo"

:) rejects a non-numeric input of ""

Why does it reject every numeric positive input except 92? My code is:

  // Includes the standardIO library, the CS50 library and the Math library
#include <stdio.h>
#include <cs50.h>
#include <math.h>



// defines the floats "change" and "cents" and sets them to 0.00. Defines the integers "cents", "i" and "coins"
float change = 0.00;
float cents = 0.0;
int i;
int coins;



// Defines the double function "round"
double round(double change);

// defines the main function
int main(void) 
{
// Asks for input, stores it in a float and checks if it's a positive number, while the float results back to less than- or equal to zero
do
{
    printf("How much change is owned? ");
    change = GetFloat();

    if(change < 0.00){
        printf("Please put in a positive number: ");
        change = GetFloat();
    }
 }
 while(change < 0.00);

  // Converts the float result to decimal numbers aka cents.
  change = roundf(change);
  cents = change;

  // Calculate the amount of coins needed
  do {
   if(cents >= 0.25) {
    cents = cents - 0.25;
    coins++;
   }

else if(cents < 0.24 && cents >= 0.10) {
    cents = cents - 0.10;
    coins++;
   }

else if(cents <= 0.09 && cents >= 0.05) {
    cents = cents - 0.05;
    coins++;
   }

else if(cents >= 0.01) {
    cents = cents - 0.01;
    coins++;
   }

 }
   while(cents > 0.00);

 printf("%d\n", coins);
return 0;
} 
1

Your first problem is that you are rounding off to dollars and losing two digits of accuracy, or to the penny. In other words, only whole dollar amounts have any chance of generating a correct answer.

Next, you have holes in your code. For instance: if(cents < 0.24 && cents >= 0.10) What happens when cents == .24?

you're going to trip on the whole point of this exercise, to understand the problems with storing floats in a computer. The best test case for this is $4.20.

This should get you going.

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

You must log in to answer this question.

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