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

为什么我的C语言纸币找零循环运行结果不符合最优预期?

代码问题原因

你的问题出在while循环内的所有if判断都是独立执行的,单次循环会依次扣减所有满足条件的面值,而不是每次仅优先扣减当前最大的可用面值。

我们拿你输入的375举例:
第一次进入循环时原始值为375,会依次执行:

  • 满足>=100,扣100后剩余275,100元张数+1
  • 满足>=50,扣50后剩余225,50元张数+1
  • 满足>=20,扣20后剩余205,20元张数+1
  • 满足>=10,扣10后剩余195,10元张数+1
  • 满足>=5,扣5后剩余190,5元张数+1
  • 满足>=2,扣2后剩余188,2元张数+1
  • 满足>=1,扣1后剩余187,1元张数+1

第二次循环剩余187,同样逻辑扣完后所有面值的张数都会变成2,最后剩余的1元刚好对应之前累加的1张1元,就得到了你现在看到的错误输出。

修复方案

方案1:修改判断逻辑为互斥分支

把if后续的所有判断改成else if,保证单次循环内仅执行最大面值的扣减:

int main(void)
{
    int quantity = get_int("Quantity: ");
    int hundred = 0;
    int fifty = 0;
    int twenty = 0;
    int ten = 0;
    int five = 0;
    int two = 0;
    int one = 0;
    
    while ( quantity > 0 )
    {
        if ( quantity >= 100 )
        {
            quantity -= 100; 
            hundred++;
        }
        else if ( quantity >= 50 )
        {
            quantity -= 50;
            fifty++;
        }
        else if ( quantity >= 20 )
        {
            quantity -= 20;
            twenty++;
        }
        else if ( quantity >= 10 )
        {
            quantity -= 10;
            ten++;
        }
        else if ( quantity >= 5)
        {
            quantity -= 5;
            five++;
        }
        else if ( quantity >= 2)
        {
            quantity -= 2;
            two++;
        }
        else if ( quantity >= 1 )
        {
            quantity -= 1;
            one++;
        }
    }
    
    printf("%d notes of 100\n", hundred);
    printf("%d notes of 50\n", fifty);
    printf("%d notes of 20\n", twenty);
    printf("%d notes of 10\n", ten);
    printf("%d notes of 5\n", five);
    printf("%d notes of 2\n", two);
    printf("%d notes of 1\n", one);
}

方案2:直接计算张数(更高效,无需循环)

不需要逐次扣减,直接用除法计算当前面值的最大可用张数,再用取余更新剩余金额即可,代码效率更高:

int main(void)
{
    int quantity = get_int("Quantity: ");
    int hundred = quantity / 100;
    quantity %= 100;
    int fifty = quantity / 50;
    quantity %= 50;
    int twenty = quantity / 20;
    quantity %= 20;
    int ten = quantity / 10;
    quantity %= 10;
    int five = quantity / 5;
    quantity %= 5;
    int two = quantity / 2;
    quantity %= 2;
    int one = quantity;
    
    printf("%d notes of 100\n", hundred);
    printf("%d notes of 50\n", fifty);
    printf("%d notes of 20\n", twenty);
    printf("%d notes of 10\n", ten);
    printf("%d notes of 5\n", five);
    printf("%d notes of 2\n", two);
    printf("%d notes of 1\n", one);
}

两种方案输入375都会得到你预期的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:45:09