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

C++使用while命令读取输入求最大值、次大值及最大值所在行号

问题解决代码及说明

改动点说明

你原有的代码只维护了最大值变量,需要新增3个变量实现需求:

  • second_max:存储第二大数值
  • line_cnt:统计当前输入的行号
  • max_line:记录最大值出现的行号

另外注意不要直接使用max作为变量名,容易和标准库的std::max产生命名冲突,这里改为first_max,同时引入<climits>头文件使用INT_MIN作为初始值,兼容输入包含负数的场景。

完整可运行代码

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

int main()
{
    int price;
    int first_max = INT_MIN;
    int second_max = INT_MIN;
    int line_cnt = 0;
    int max_line = 0;

    cin >> price;
    while (price != -1) {
        line_cnt++;
        if (price > first_max) {
            // 原有最大值降级为第二大值
            second_max = first_max;
            first_max = price;
            // 记录最大值所在行号
            max_line = line_cnt;
        } else if (price > second_max && price != first_max) {
            // 小于最大值但大于当前第二大值,更新第二大值
            second_max = price;
        }
        cin >> price;
    }

    // 按要求格式输出
    cout << first_max << "(the biggest number)" << endl;
    cout << second_max << "(the biggest number after " << first_max << ")" << endl;
    cout << max_line << "(the row that the user has entered the largest number)" << endl;

    return 0;
}

逻辑验证

对应你给出的示例输入:

4
7
11
5
-1

程序输出结果和要求完全一致:

11(the biggest number)
7(the biggest number after 11)
3(the row that the user has entered the largest number)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:54:05