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
相关产品推荐
相关产品推荐

