You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何手动测试代码可拒绝负数输入,但check50检测不通过?

问题分析与解决

问题根源

你把输入验证逻辑放在了main函数的do-while循环中,但CS50的check50工具会单独测试get_cents函数——题目要求该函数本身必须确保返回非负整数,而非依赖外部循环过滤非法输入。

手动测试时,main里的循环会反复调用get_cents直到输入合法,所以看起来没问题;但check50直接调用get_cents函数,当传入-10时,你的原函数直接返回负数,不符合检测要求,因此判定未拒绝非法输入。

解决方案

将输入验证逻辑移至get_cents函数内部,确保函数自身返回合法值,同时移除main中多余的循环:

修改后的get_cents函数:

int get_cents(void)
{
    int cents;
    do
    {
        cents = get_int("how many cents? ");
    } while (cents < 0);
    return cents;
}

修改后的main函数:

int main(void)
{
    // Ask how many cents the customer is owed
    int cents = get_cents();

    // 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("%i\n", coins);
}

补充说明

原代码中的do-while循环本身逻辑没有问题,但位置不符合题目对get_cents函数的职责要求。CS50的项目通常要求每个辅助函数完成单一职责,get_cents的职责就是获取并返回合法的非负美分数值,验证逻辑自然应该放在该函数内。

内容的提问来源于stack exchange,提问作者Sizwe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:15:29