繁体   English   中英

如果用户输入为否,请再次提示

[英]If user input is negative, prompt again

所以我正在计算找零,如果用户的输入是0.41 ,结果将是: 1 quarter, 1 dime, 1 nickel, 1 penny

该代码可以正常工作,直到您提供负值。 我添加了一个if语句进行检查,然后我所能做的就是exit(0) 我想一次又一次提示用户输入一个正值,我该怎么做?

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

将声明作为新手放置在哪里可能有点尴尬,所以这里是:

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.

您不能将float amount放入{ }内,否则该变量将被限制在该范围内,并且在}之后无法访问。

编写相同循环的更紧凑的方法是:

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

但您可以使用对您而言更明智的任何版本。

float amount;
do
{
    amount = GetFloat();
}
while (0 < amount);

编辑:马特赢得了包括邮件,告诉他们为什么绕环当然用户。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM