酷代码 AI
菜单

#include <iostream> #include <vector> #include <algorithm> int main() { int n; std::cin >> n; std::vector<int> times(n); for (int i = 0; i < n; ++i) { std::cin >> times[i]; } std::sort(times.begin(), times.end()); int total = 0; for (int i = 0; i < 5; ++i) { total += times[i]; } std::cout << total << std::endl; return 0; }

这段代码存在逻辑错误。 `for (int i = 0; i < 5; ++i)` 假设 `n` 至少为 5,但题目未保证这一点。 如果 `n < 5`,访问 `times[i]` 会导致数组越界。 修改建议: 1. 检查 `n` 是否小于 5,若小于则只累加前 `n` 个元素。 2. 使用 `std::min(5, n)` 控制循环次数。 修正后的代码: ```cpp #include <iostream> #include <vector> #include <algorithm> int main() { int n; std::cin >> n; std::vector<int> times(n); for (int i = 0; i < n; ++i) { std::cin >> times[i]; } std::sort(times.begin(), times.end()); int total = 0; int limit = std::min(5, n); for (int i = 0; i < limit; ++i) { total += times[i]; } std::cout << total << std::endl; return 0; } ``` [2026-01-17 10:23:32 | AI问答 | 263点数解答]

服务商
相关提问
发财导航,免费问AI
实用工具查看更多