-1

After working on greedy/cash in CS50. today I was pumped as it was functioning correctly. I went back and tested with the values it suggests -1.00, 0.00, foo, and then when I tried a positive integer such as .80, the counter was incorrect, adding extra numbers to it. I am guessing that between the testing for negative values, zero, and characters I must have done something in my code to alter it as again, I had run 5 or more codes that functioned correctly. I have combed back over my code through and through and can't figure out what is throwing my counter off now. Could anyone point me in a direction of where to look?

The goal is to say the minimum amount of coins that can be used for the given amount of change. Ex for 65 cents it would be 4, (two quarters, one dime, one nickel)

My code is below:

#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
    float change;
    do {
        change = get_float("Change owed:\n");
    } while (change <= 0);

    float cents;
    cents = round(change * 100);
    printf("%f cents \n", cents);
    int counter = 0;
    do {
        cents = cents - 25;
        counter = counter + 1;
    } while (cents >= 25);

    do {
        cents = cents - 10;
        counter = counter + 1;
    } while (cents >= 10);

    do {
        cents = cents - 5;
        counter = counter + 1;
    }
    while (cents >= 5);

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

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

Any insight is appreciated!

whiskeyo
  • 873
  • 1
  • 9
  • 19
  • PLEASE indent your code properly. What is up with all the parenthesis? No need for those. Please read [ask] . Now is a good time to learn proper debugging skills. at a minimum, you can put printf calls in all your loops and print out the counter and cents values. Also read [why are floating point numbers inaccurate](https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – OldProgrammer Apr 22 '20 at 01:48

1 Answers1

0

Remember, a do..while executes at least once. 65 cents is a good example, it will count the 2 quarters, the dime, the nickle. cents is 0. But what happens next? It will count a penny! because it executes the loop before the while test.

DinoCoderSaurus
  • 6,110
  • 2
  • 10
  • 15