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

C++模板函数求最值时输入验证功能不生效问题求助

问题根因

  • 输入校验函数errorA使用值传递参数:函数内部重新读取的数值只会写到参数的临时副本中,不会回传给main函数里的原始变量,输入失败后原始变量保留的是未初始化的异常值(多数场景下为0)
  • 代码使用了INT_MAX常量,但未引入对应的头文件<climits>,部分编译环境会直接报错
  • 仅做了1次错误重试,如果第二次输入仍然非法,还是会得到异常值

修复后的完整代码

#include<iostream>
#include<climits>
using namespace std;

// 参数改为引用传递,确保修改能同步到外部变量
template <typename E>
void errorA(E& a) {
    // 循环校验直到输入合法
    while (!std::cin.good()) {
        cout << "\n\nERROR! Faulty input! Try again!\n";
        // 清空错误状态
        cin.clear();
        // 丢弃缓冲区残留的非法内容
        std::cin.ignore(INT_MAX, '\n');
        cout << "Enter NUMBER again: ";
        cin >> a;
    }
}


template <typename T>
void maximum(T& a, T& b) {
    if (a > b) {
        cout << a << " is the maximum of these 2 numbers: " << a << " & " << b << endl;
    } else if (b > a) {
        cout << b << " is the maximum of the 2 numbers: " << a << " & " << b << endl;
    } else {
        cout << "Both these numbers: " << a << " & " << b << ", are equal! " << endl;
    }
}

int main() {
    int a, b;
    cout << "Please enter 2 integers to find its maximum.\n";
    cout << "Enter 1st number: ";
    cin >> a;
    errorA(a);
    cout << "Enter 2nd number: ";
    cin >> b;
    errorA(b);
    maximum(a, b);

    double c, d;
    cout << "\n\nPlease enter 2 doubles to find its maximum.\n";
    cout << "Enter 1st number: ";
    cin >> c;
    errorA(c);
    cout << "Enter 2nd number: ";
    cin >> d;
    errorA(d);
    maximum(c, d);
    return 0;
}

补充说明

如果需要适配中文输出提示,直接把cout里的英文提示替换为对应中文即可,逻辑不需要修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:27:04