C语言如何跳过数组内指定值实现GPA平均值正确计算
GPA计算器代码问题修复
核心错误
你当前的代码已经实现了0值过滤求和的逻辑,但计算平均值时仍然使用了包含0值的总输入次数counter作为分母,没有统计实际有效非0分数的数量,导致计算结果偏低。
修正后的完整代码
#include <stdio.h> int main() { int iArray[30] = { 0 }; int choice; int counter = 0; int sum = 0; int validCount = 0; // 新增:统计非0有效分数的数量 float average; do { printf("\nEnter GPA score here: "); scanf(" %d", &iArray[counter]); counter++; printf("\n1\tEnter a new GPA? Please enter \"1\"."); printf("\n2\tCalculate the current GPA average? Please enter \"2\".\n"); printf("\n\nPlease enter choice here: "); scanf(" %d", &choice); } while (choice == 1 && counter < 30); if (choice == 2) { for (int x = 0; x < counter; x++) { if (iArray[x] >= 1) { // 过滤0值 sum += iArray[x]; validCount++; // 有效分数计数+1 } } } // 避免除以0的异常情况 if (validCount == 0) { printf("\n\n无有效GPA分数可计算"); } else { // 用有效分数数量做分母,同时转float避免整数截断 average = (float)sum / validCount; printf("\n\nThe average GPA is %.2f ", average); } return 0; }
验证测试用例
针对你给出的测试场景:
- 输入
10, 2, 0, 38时,求和结果为10+2+38=50,有效分数计数为3,计算后输出16.00,符合预期结果。
内容的提问来源于stack exchange,提问作者SimTim124
相关产品推荐
相关产品推荐

