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

求修正:计算支付所需最少纸币与硬币数量的C++程序

问题分析与修正方案

你的代码逻辑完全跑偏了——switch(pari)是拿输入的总金额去匹配case值,比如输入54321时,根本没有对应的case,直接走default输出WRONG,这显然不是你要的效果。要实现“计算支付最少纸币硬币数量”的需求,正确的做法是用贪心算法,从最大面额到最小面额依次计算使用数量。

修正后的代码

#include <iostream>
using namespace std;

int main()
{
    int remaining;
    cin >> remaining;
    // 按从大到小排列的面额数组
    int denominations[] = {5000, 1000, 500, 100, 50, 10, 5, 2, 1};
    int size = sizeof(denominations) / sizeof(denominations[0]);
    
    for (int i = 0; i < size; ++i) {
        int denom = denominations[i];
        int count = remaining / denom;
        // 按示例格式输出数量和面额
        cout << count << "x" << denom << endl;
        // 更新剩余金额
        remaining = remaining % denom;
    }
    return 0;
}

代码说明

  1. 面额数组:把所有需要处理的面额按从大到小顺序存入数组,确保每次优先使用最大面额,满足“最少数量”的要求。
  2. 遍历计算:对每个面额,用当前剩余金额除以面额得到使用数量,然后用取余运算更新剩余金额(剩余金额 = 剩余金额 % 面额)。
  3. 输出格式:严格按照示例要求用x连接数量和面额,即使数量为0也要输出(比如示例中的0x500)。

测试输入54321时,输出会和示例完全一致:

10x5000
4x1000
0x500
3x100
0x50
2x10
0x5
0x2
1x1

内容的提问来源于stack exchange,提问作者Тодор Тодоровски

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:20:37