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

如何简化C++凑1美元找零游戏中的嵌套if/else语句?

优化方案:简化嵌套并提升代码可读性

你的代码核心逻辑没问题,但深层嵌套确实严重影响可读性。可以从消除嵌套、避免浮点误差、复用代码这几个方向优化,下面是具体改进:

关键优化点

  • 用整数计算替代浮点数:把所有金额转换为美分(整数),彻底避免double类型的精度问题(比如0.01这类十进制小数在二进制浮点数中无法精确表示,可能导致==1.00的判断出错)。
  • 封装输入验证函数:把「提示输入+验证非负」的逻辑抽成函数,避免重复代码,直接扁平化流程。
  • 提前终止流程:输入验证失败时直接提示并结束程序(或扩展为重复输入直到合法),不用嵌套else。
  • 减少冗余变量:不需要单独存储每种硬币的总金额,直接累加计算总美分数。

优化后的代码

#include <iostream>
#include <string>

using namespace std;

// 封装输入硬币数量的函数,返回非负整数,失败则返回-1
int getCoinCount(const string& coinName) {
    int count;
    cout << "\nEnter the amount of " << coinName << ": ";
    cin >> count;
    if (count < 0) {
        cout << "\nAmount of " << coinName << " must be greater than or equal to zero!";
        return -1;
    }
    return count;
}

int main() {
    cout << "Enter a quantity of coins needed to make EXACTLY one dollar.\n";

    // 获取各硬币数量,验证失败直接结束程序
    int pennies = getCoinCount("pennies");
    if (pennies == -1) return 0;

    int nickels = getCoinCount("nickels");
    if (nickels == -1) return 0;

    int dimes = getCoinCount("dimes");
    if (dimes == -1) return 0;

    int quarters = getCoinCount("quarters");
    if (quarters == -1) return 0;

    // 计算总美分数(1美元=100美分)
    int totalCents = pennies * 1 + nickels * 5 + dimes * 10 + quarters * 25;

    // 判断结果
    if (totalCents == 100) {
        cout << "\nCONGRATULATIONS!\nYour selection of coins adds up to $1.00.\n";
    } else {
        cout << "\nGAME OVER!\n";
        totalCents < 100 ? 
            cout << "Your selection of coins was less than $1.00.\n" : 
            cout << "Your selection of coins was more than $1.00.\n";
    }

    return 0;
}

优化细节说明

  1. 整数计算的优势:用美分作为单位,所有计算都是整数运算,完全避免浮点数精度丢失的问题,判断金额是否等于1美元的逻辑更准确。
  2. 函数封装的好处:把重复的输入+验证逻辑写成getCoinCount,代码更简洁,后续如果要修改提示文本或验证规则,只需要改一处即可。
  3. 扁平化结构:每个输入验证失败后直接return 0终止程序,没有多层else嵌套,代码逻辑从上到下线性执行,可读性大幅提升。
  4. 冗余变量删减:去掉了penniesTotal等单独的金额变量,直接通过整数乘法累加总美分数,减少不必要的内存占用和代码复杂度。

如果想要支持重复输入直到正确(而不是失败就退出),可以修改getCoinCount函数,用循环实现:

int getCoinCount(const string& coinName) {
    int count;
    while (true) {
        cout << "\nEnter the amount of " << coinName << ": ";
        cin >> count;
        if (count >= 0) {
            return count;
        }
        cout << "\nAmount of " << coinName << " must be greater than or equal to zero! Please try again.";
    }
}

这样用户输入负数时会被提示重新输入,体验更好,同时代码依然保持扁平化结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 04:54:51