C++程序计算数组每行最大值异常,求问题原因排查
Hey there! Let's break down why your program is spitting out incorrect max scores (stuck at 10 for the first three games) and cutting off early. I've seen this kind of issue a bunch of times—usually it's down to two common mistakes: improper max value initialization and loop boundary errors.
问题分析
From your output, we can spot two clear red flags:
- The first three games all show a max score of 10, but your third game's input only goes up to 9.4—this means your program is holding onto an old max value instead of recalculating per row.
- The output cuts off after the third game, which points to a loop that's terminating too early, or an input read error that's halting execution.
常见错误原因及修复方案
1. 错误的最大值初始化
If you declared your max_score variable outside the loop that processes each game, and initialized it to 10.0 (from the first game's last score), it would never reset for subsequent rows. Any row without a score higher than 10 would just keep showing 10—exactly what's happening here.
Fix: Initialize max_score to the first element of the current row, inside the loop for each game. This way, it starts fresh every time.
2. 循环边界或输入读取错误
If your output loop only runs 3 times instead of 5 (e.g., you wrote i < 3 instead of i < 5), or your input read code is failing to capture all scores, the program would stop early mid-output.
Fix: Double-check your loop conditions to ensure they cover all 5 games, and make sure your input reading logic properly captures every score without getting stuck on newlines.
修正后的示例代码
Here's a working version of your program that fixes both issues:
#include <iostream> #include <vector> #include <iomanip> // 用于控制小数精度 using namespace std; int main() { const int TOTAL_GAMES = 5; const int SCORES_PER_GAME = 5; vector<vector<double>> game_scores(TOTAL_GAMES, vector<double>(SCORES_PER_GAME)); // 读取每场比赛的分数 for (int game = 0; game < TOTAL_GAMES; ++game) { cout << "输入第" << game + 1 << "场比赛的分数:"; for (int score_idx = 0; score_idx < SCORES_PER_GAME; ++score_idx) { cin >> game_scores[game][score_idx]; } } // 计算并输出每场比赛的最高分 cout << "\n程序输出:\n"; for (int game = 0; game < TOTAL_GAMES; ++game) { double max_score = game_scores[game][0]; // 以当前行第一个分数为初始最大值 for (int score_idx = 1; score_idx < SCORES_PER_GAME; ++score_idx) { if (game_scores[game][score_idx] > max_score) { max_score = game_scores[game][score_idx]; } } // 保留一位小数输出,匹配输入格式 cout << "第" << game + 1 << "场比赛的获胜者分数:" << fixed << setprecision(1) << max_score << endl; } return 0; }
测试输出
使用你提供的输入,这个程序会输出:
第1场比赛的获胜者分数:10.0
第2场比赛的获胜者分数:10.0
第3场比赛的获胜者分数:9.4
第4场比赛的获胜者分数:9.6
第5场比赛的获胜者分数:9.7
完全符合预期结果!
内容的提问来源于stack exchange,提问作者Gina Cucchiara

