Halnex Halnex - 3 months ago 22
C Question

If user input is negative, prompt again

So I'm calculating money change, if the user's input is

0.41
the result will be:
1 quarter, 1 dime, 1 nickel, 1 penny
.

The code works fine, until you provide a negative value.
I added an if statement to check for that, and all I could do is
exit(0)
afterwards. I want to re-prompt the user to enter a positive value, again and again, how can I do that?

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

int main (void) {

printf("How much change do you owe: ");

float amount = GetFloat();
float cents = 100.0 * amount;
float quarter = 0;
float dime = 0;
float nickel = 0;
float penny = 0;

if (amount < 0) {
printf("Please provide a positive value.");
exit(0);
}

while (cents > 0) {
if (cents >= 25.0) {
cents -= 25.0;
quarter += 1;
} else if (cents >= 10.0) {
cents -= 10.0;
dime += 1;
} else if (cents >= 5.0) {
cents -= 5.0;
nickel += 1;
} else if (cents >= 1.0) {
cents -= 1.0;
penny += 1;
}
}
printf("%f quarters, %f dimes, %f nickels, %f pennies, Total of %f coins.\n", quarter, dime, nickel, penny, quarter + dime + nickel + penny);
}

M.M M.M
Answer

It can be a bit awkward to get your head around where to put declarations as a newbie, so here it is:

float amount;

for (;;)
{
    amount = GetFloat();

    if ( amount >= 0 ) 
        break;

    printf("Please provide a positive value.\n");
}

float cents = 100.0 * amount;
float quarter = 0;
// etc.

You can't put float amount inside the { } otherwise that variable would be scoped to that scope, and not accessible after the }.

A more compact way of writing the same loop would be:

while( (amount = GetFloat()) < 0 )
    printf("Please provide a positive value.");

but you can use whichever version looks more sensible to you.