c-当我手动测试时,为什么我的代码拒绝否定的用户输入,而不是通过";check50 cs50/problems



这是我试图测试的代码。

我已经多次尝试更改我使用的循环类型,甚至更改它的放置位置(要么是在"int get_cents"函数中,要么是现在的位置(。

这可能是因为我使用了一个do while循环吗?代码最初不会拒绝负输入,这就是为什么当我运行check50时,我会得到这样的结果:

正在运行/现金测试0(_T(。。。正在发送输入-10。。。正在检查输入是否被拒绝。。。

#include <cs50.h>
#include <stdio.h>
int get_cents(void);
int calculate_quarters(int cents);
int calculate_dimes(int cents);
int calculate_nickels(int cents);
int calculate_pennies(int cents);
int main(void)
{
// Ask how many cents the customer is owed
int cents;
do
{
cents = get_cents();
}
while (cents < 1);
{
// Calculate the number of quarters to give the customer
int quarters = calculate_quarters(cents);
cents = cents - quarters * 25;
// Calculate the number of dimes to give the customer
int dimes = calculate_dimes(cents);
cents = cents - dimes * 10;
// Calculate the number of nickels to give the customer
int nickels = calculate_nickels(cents);
cents = cents - nickels * 5;
// Calculate the number of pennies to give the customer
int pennies = calculate_pennies(cents);
cents = cents - pennies * 1;
// Sum coins
int coins = quarters + dimes + nickels + pennies;
// Print total number of coins to give the customer
printf("%in", coins);
}
}
int get_cents(void)
{
// TODO
return get_int("how many cents? ");
}
int calculate_quarters(int cents)
{
// TODO
return cents/25;
}
int calculate_dimes(int cents)
{
// TODO
return cents/10;
}
int calculate_nickels(int cents)
{
// TODO
return cents/5;
}
int calculate_pennies(int cents)
{
// TODO
return cents/1;
}

为什么我的代码只有在手动测试时才能正常工作?

从检查器应用程序中得到的错误说明来看,测试的要求是程序应该立即指示输入了无效的负值,并且程序应该结束。而不是";而";在允许重试的循环中,您可以尝试以下代码片段。

// Ask how many cents the customer is owed
int cents;
cents = get_cents();
if (cents < 0)
{
printf("A negative value was entered and rejectedn");
return -1;
}

这将导致如下的输出-10〃;已输入。

@Una:~/C_Programs/Console/cash_test/bin/Release$ ./cash_test 
how many cents? -10
A negative value was entered and rejected
@Una:~/C_Programs/Console/cash_test/bin/Release$ 

你可以试一试。

如果输入负数,则此处的get_cents函数将不会重试,因为该测试是主测试。规范中明确指出,在get_cents函数:内,重新启动应

实现get_cents的方式是,函数使用get_int提示用户输入美分数,然后将该数作为int返回。如果用户输入了否定的int,那么您的代码应该再次提示用户。

最新更新