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

C++自动售货机程序while循环与if/else语句故障求助

自动售货机模拟程序问题排查与修复

问题概述

我是C++编程新手,正在开发自动售货机模拟程序,用while循环和if/else实现逻辑控制。程序分为头部信息、投币循环、选饮循环、退出循环四个模块,但整合后逻辑问题频发:

  • 投入5美元购买2.25美元的Gatorade后,输入无效选饮选项会绕过资金检查
  • 剩余资金低于最低消费1.5美元时,程序仍强制要求用户选品
  • 无效输入无法被多次处理,会直接跳转到下一循环,条件检查失效

以下是原代码:

#include <iostream>

using namespace std;

/*
    What I plan on using for conditions, etc.
*/
char orderCharacter;
char orderNumber;
float fundsAvailable = 0;
char moreMoney;
char moreDrinks;
bool quit = false;
bool quitTwo = false;


int main()
{
    /*
    simple header.
    */
    cout<<"========================================"<<endl;
    cout<<"Welcome to the Vending Machine"<<endl;
    cout<<"========================================"<<endl;

    /*
    While loop for inserting coins and bills. After user input, if and else output
    */
    while (quit == false){
    cout<<"Please insert your coins/bills"<<endl;
    cout<<"(1)$1, (2)$5, (3)$10, (4)$20 :"<<endl;
    cin>>orderNumber;

    if (orderNumber == '1'){
        fundsAvailable = fundsAvailable + 1;
        cout<<"You've inserted: $1"<<endl;
        cout<<"Funds available: $"<<fundsAvailable<<endl;
        quit = true;
    }else if (orderNumber == '2'){
        fundsAvailable = fundsAvailable + 5;
        cout<<"You've inserted: $5"<<endl;
        cout<<"Funds available: $"<<fundsAvailable<<endl;
        quit = true;
    }else if (orderNumber == '3'){
        fundsAvailable = fundsAvailable + 10;
        cout<<"You've inserted: $10"<<endl;
        cout<<"Funds available: $"<<fundsAvailable<<endl;
        quit = true;
    }else if (orderNumber == '4'){
        fundsAvailable = fundsAvailable + 20;
        cout<<"You've inserted: $20"<<endl;
        cout<<"Funds available: $"<<fundsAvailable<<endl;
        quit = true;
    }else{
        cout<<"Invalid Selection"<<endl;
        quit = false;
    }
//same process but for money...
    cout<<"Add more coins/bills? (Y/N): ";
    cin>>moreMoney;

    if ((moreMoney == 'N' || moreMoney == 'n') && (fundsAvailable>=1.50)){
            quit = true;
    }else if ((moreMoney == 'Y') || (moreMoney == 'y')){
            quit = false;
    }else if ((moreMoney == 'N' || moreMoney == 'n') && (fundsAvailable<=1.49)){
            cout<<"Insufficient funds to make a purchase."<<endl;
            cout<<"Please take your change."<<endl;
            quit = true;
            quitTwo = true;
            cout<<"Thank you for using our vending machine!"<<endl;
    }else{
            cout<<"Your answer is invalid. Please answer Y or N"<<endl;
            cout<<"Add more coins/bills? (Y/N): ";
            cin>>moreMoney;
        }
    }
//second while loop drink loop
    while (quitTwo == false){
        cout<<"Please make a selection:"<<endl;
        cout<<"(A)quaVeena $1.50, (B)epsi $2.00, (C)ool Cola $2.00, (G)atorade $2.25"<<endl;
        cin>>orderCharacter;

    if ((fundsAvailable <= 1.49) && (quitTwo == false)){
        cout<<"Insufficient funds to make a purchase."<<endl;
        cout<<"Please take your change."<<endl;
        cout<<"Thank you for using our vending machine!"<<endl;
    }
//calculations
    switch (orderCharacter){
        case 'A':{
        fundsAvailable = fundsAvailable - 1.50;
        break;
        }
        case 'a':{
        fundsAvailable = fundsAvailable - 1.50;
        break;
        }
        case 'B':{
        fundsAvailable = fundsAvailable - 2.00;
        break;
        }
        case 'b':{
        fundsAvailable = fundsAvailable - 2.00;
        break;
        }
        case 'C':{
        fundsAvailable = fundsAvailable - 2.00;
        break;
        }
        case 'c':{
        fundsAvailable = fundsAvailable - 2.00;
        break;
        }
        case 'G':{
        fundsAvailable = fundsAvailable - 2.25;
        break;
        }
        case 'g':{
        fundsAvailable = fundsAvailable - 2.25;
        break;
        }
}
    cout<<"Add more drinks (Y/N): ";
    cin>>moreDrinks;
//trying to checking available funds before selection, if lower than 1.50, automatically end and other options.
    if ((fundsAvailable >=1.50) && (moreDrinks == 'Y' || moreDrinks =='y')){
        quitTwo = false;
    }else if ((fundsAvailable <=1.49) && (moreDrinks == 'Y' || moreDrinks =='y')){
        quitTwo = true;
        cout<<"Funds available: $"<<fundsAvailable<<endl;
        cout<<"Please take your change."<<endl;
        cout<<"Thank you for using our vending machine!"<<endl;
    }else if ((fundsAvailable >=1.50) && (moreDrinks == 'N' || moreDrinks =='n')){
        quitTwo = true;
        cout<<"Funds available: $"<<fundsAvailable<<endl;
        cout<<"Please take your change."<<endl;
        cout<<"Thank you for using our vending machine!"<<endl;
    }else{
        cout<<"Your answer is invalid. Please answer Y or N"<<endl;
        cout<<"Add more drinks (Y/N): ";
        cin>>moreDrinks;
        quitTwo = false;
    }
}

    return 0;
}

核心问题分析

  1. 资金检查时机错误:选饮循环里的资金检查放在用户输入选品之后,导致即使余额不足,程序仍会先显示选品界面;无效选品时也不会触发资金不足的判断
  2. 无效输入处理不彻底:选品环节没有对非A/B/C/G的输入做处理,直接跳过扣款逻辑进入后续步骤;Y/N类型的输入只做了一次错误提示,无法循环纠正直到输入有效
  3. 循环退出条件不同步:余额不足时没有及时设置quitTwo为true终止循环,导致程序仍会继续要求用户选品

修复后的代码

#include <iostream>
#include <string>

using namespace std;

char orderCharacter;
char orderNumber;
float fundsAvailable = 0;
bool quit = false;
bool quitTwo = false;

// 封装Y/N输入验证逻辑,避免重复代码
bool getYesNoInput(const string& prompt) {
    char input;
    while (true) {
        cout << prompt;
        cin >> input;
        if (input == 'Y' || input == 'y') {
            return true;
        } else if (input == 'N' || input == 'n') {
            return false;
        } else {
            cout << "Invalid input! Please enter Y or N." << endl;
        }
    }
}

int main()
{
    // 头部信息
    cout<<"========================================"<<endl;
    cout<<"Welcome to the Vending Machine"<<endl;
    cout<<"========================================"<<endl;

    // 投币循环
    while (!quit){
        cout<<"Please insert your coins/bills"<<endl;
        cout<<"(1)$1, (2)$5, (3)$10, (4)$20 :"<<endl;
        cin>>orderNumber;

        bool validCoin = false;
        if (orderNumber == '1'){
            fundsAvailable += 1;
            cout<<"You've inserted: $1"<<endl;
            validCoin = true;
        }else if (orderNumber == '2'){
            fundsAvailable += 5;
            cout<<"You've inserted: $5"<<endl;
            validCoin = true;
        }else if (orderNumber == '3'){
            fundsAvailable += 10;
            cout<<"You've inserted: $10"<<endl;
            validCoin = true;
        }else if (orderNumber == '4'){
            fundsAvailable += 20;
            cout<<"You've inserted: $20"<<endl;
            validCoin = true;
        }else{
            cout<<"Invalid Selection"<<endl;
        }

        cout<<"Funds available: $"<<fundsAvailable<<endl;

        // 仅输入有效金额后才询问是否加钱,否则重新投币
        if (validCoin) {
            bool addMore = getYesNoInput("Add more coins/bills? (Y/N): ");
            if (!addMore) {
                if (fundsAvailable < 1.50) {
                    cout<<"Insufficient funds to make a purchase."<<endl;
                    cout<<"Please take your change: $"<<fundsAvailable<<endl;
                    quitTwo = true;
                    cout<<"Thank you for using our vending machine!"<<endl;
                }
                quit = true;
            }
        }
    }

    // 选饮循环
    while (!quitTwo){
        // 先检查资金,不足直接终止循环
        if (fundsAvailable < 1.50) {
            cout<<"Insufficient funds to make a purchase."<<endl;
            cout<<"Please take your change: $"<<fundsAvailable<<endl;
            cout<<"Thank you for using our vending machine!"<<endl;
            quitTwo = true;
            break;
        }

        cout<<"Please make a selection:"<<endl;
        cout<<"(A)quaVeena $1.50, (B)epsi $2.00, (C)ool Cola $2.00, (G)atorade $2.25"<<endl;
        cin>>orderCharacter;

        bool validSelection = false;
        switch (orderCharacter){
            case 'A':
            case 'a':
                fundsAvailable -= 1.50;
                validSelection = true;
                break;
            case 'B':
            case 'b':
            case 'C':
            case 'c':
                fundsAvailable -= 2.00;
                validSelection = true;
                break;
            case 'G':
            case 'g':
                fundsAvailable -= 2.25;
                validSelection = true;
                break;
            default:
                cout<<"Invalid selection! Please choose A/B/C/G."<<endl;
                // 无效输入时回到循环开头,重新选品
                continue;
        }

        cout<<"Funds available: $"<<fundsAvailable<<endl;

        bool addMoreDrinks = getYesNoInput("Add more drinks (Y/N): ");
        if (!addMoreDrinks) {
            cout<<"Please take your change: $"<<fundsAvailable<<endl;
            cout<<"Thank you for using our vending machine!"<<endl;
            quitTwo = true;
        }
        // 用户选Y但资金不足时,下次循环会自动检查并退出
    }

    return 0;
}

修复说明

  1. 提前资金检查:选饮循环每次启动先判断余额,不足直接终止,不让用户进入选品环节
  2. 完善无效输入处理:
    • 选品环节添加default分支,提示错误后用continue回到循环开头重新选品
    • 封装getYesNoInput函数,循环处理Y/N输入直到用户输入有效选项,减少冗余代码
  3. 优化投币循环逻辑:只有输入有效金额后才询问是否加钱,否则直接重新投币;quit状态更新更清晰
  4. 简化扣款逻辑:把大小写相同的选品合并到同一个case,精简代码结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:10:54