mercredi 22 juillet 2015

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 the 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);
}

Aucun commentaire:

Enregistrer un commentaire