DevC++中分数数组输入、循环终止及满分统计功能故障求助
问题修正:实现输入分数并统计满分数量的程序
你的程序存在两个核心问题,以下是针对性修正方案:
1. 修复getScores函数的输入终止逻辑
修改后的getScores存在嵌套循环错误、无返回值、终止条件无效的问题,正确逻辑应该是:逐个读取输入,遇到-1或满10个分数时停止,同时返回实际输入的分数数量。
修正后的getScores函数:
int getScores(int array[]) { int index = 0; while (index < 10) { cout << "Enter a score from 0-100 (-1 to quit): "; cin >> array[index]; // 输入-1则终止循环 if (array[index] == -1) { break; } index++; } // 返回实际输入的有效分数数量(不包含-1) return index; }
2. 修复countPerfect函数的统计逻辑
原函数存在两个致命错误:判断条件错误(把数组下标index和100比较)、错误覆盖计数变量perfect。正确逻辑是遍历数组元素,统计等于100的元素个数。
修正后的countPerfect函数:
int countPerfect(int array[], int numScores) { int perfect = 0; for(int index = 0; index < numScores; index++) { // 判断当前元素是否为满分100 if(array[index] == 100) perfect++; } return perfect; }
完整修正后的程序代码
#include <iostream> using namespace std; // Function prototypes int getScores(int[]); int countPerfect(int[], int); int main() { const int size = 10; int array[size]; int numScores; // Explain program to user cout << "This program will allow you to enter up to 10 scores. " << endl << "Then, it will report how many perfect scores were entered." << endl; // Call a function to input the scores into array numScores = getScores(array); // Report results cout << "The " << numScores << " scores you entered include " << countPerfect(array, numScores) << " perfect scores.\n"; return 0; } // getScores will retrieve up to 10 scores from user int getScores(int array[]) { int index = 0; while (index < 10) { cout << "Enter a score from 0-100 (-1 to quit): "; cin >> array[index]; if (array[index] == -1) { break; } index++; } return index; } // countPerfect accepts array, then counts and returns the number of perfect scores (equal to 100) int countPerfect(int array[], int numScores) { int perfect = 0; for(int index = 0; index < numScores; index++) { if(array[index] == 100) perfect++; } return perfect; }
内容的提问来源于stack exchange,提问作者user24020519
相关产品推荐
相关产品推荐

