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

员工折扣程序:int变量输入字符错误提示实现及多员工变量处理求助

员工折扣程序问题解决

修复后的完整代码

/* Program name: main.cpp
*  Author: Carl Snyder
*  Date last updated: 09/11/2022
* Purpose: Top employee discount calculator
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <limits> // 用于清空输入缓冲区
using namespace std;

int main() 
{
    ifstream inFile;
    int winning_Nums[3]; // 存储三位中奖员工编号
    int employee_Num;
    double total_Bill;
    double discount_Percent;
    double discount_Amount;
    double bill_After_Discount;
    bool isWinner = false; // 标记是否中奖

    // 检查文件是否成功打开
    inFile.open("EOM.txt");
    if (!inFile.is_open()) {
        cout << "无法打开文件EOM.txt,程序将退出。" << endl;
        return 1;
    }

    // 读取三位中奖员工编号和折扣比例
    inFile >> winning_Nums[0] >> winning_Nums[1] >> winning_Nums[2] >> discount_Percent;
    // 将折扣比例转换为小数(比如20%转为0.2)
    discount_Percent /= 100.0;

    cout << "Enter your employee number to see if you get a discount: ";
    cin >> employee_Num;

    // 检查员工编号输入是否有效(不是数字的情况)
    if (cin.fail()) {
        cout << "你输入的不是数字!程序将退出。" << endl;
        return 1;
    }

    cout << fixed << showpoint << setprecision(2);

    // 检查员工编号范围
    if (employee_Num < 10000 || employee_Num > 99999) {
        cout << "你输入的编号超出范围!员工编号是5位数字(10000-99999)。程序将退出。" << endl;
        return 1;
    }

    // 判断是否为中奖员工
    for (int num : winning_Nums) {
        if (employee_Num == num) {
            isWinner = true;
            break;
        }
    }

    if (isWinner) {
        cout << "你获得了" << discount_Percent * 100 << "%的折扣。" << endl;
        cout << "请输入账单总额:" << endl;
        cin >> total_Bill;

        // 检查账单输入是否有效
        if (cin.fail()) {
            cout << "你输入的不是数字!程序将退出。" << endl;
            return 1;
        }

        if (total_Bill <= 0) {
            cout << "账单总额必须大于0。程序将退出。" << endl;
            return 1;
        }

        discount_Amount = total_Bill * discount_Percent;
        bill_After_Discount = total_Bill - discount_Amount;
        cout << "折扣将为你减免$" << discount_Amount << "。" << endl;
        cout << "你的新账单总额是$" << bill_After_Discount << "。" << endl;
    } else {
        cout << "抱歉,你本月未中奖,下个月再试试吧。" << endl;
    }

    inFile.close();
    return 0;
}

关键修改说明

  • 处理三位中奖员工:用数组winning_Nums[3]存储三个中奖编号,从文件读取后通过循环判断用户输入的编号是否在中奖列表中
  • 输入错误处理:每次cin读取后用cin.fail()检查输入有效性,若输入字符而非数字,直接输出错误提示并退出。如需支持重复输入,可在判断后添加cin.clear()重置状态+cin.ignore(numeric_limits<streamsize>::max(), '\n')清空缓冲区
  • 修正条件逻辑:调整判断顺序,先验证输入有效性,再检查编号范围,最后判断是否中奖,解决原代码分支覆盖错误的问题
  • 文件有效性检查:添加文件打开状态判断,避免文件不存在时的未定义行为
  • 折扣计算修正:将读取的折扣比例除以100转换为小数(如文件输入20代表20%,需转为0.2参与计算)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:20:59