二维数组偶数求和与平均值计算代码调试求助
你的二维数组偶数统计代码问题分析与修正
让我来帮你拆解代码里的问题,顺便完成你计算偶数平均值的需求~
代码里的核心问题
- 无限循环的
while语句:你用while (arr[i][j] % 2 == 0)判断偶数,这是致命错误!一旦遇到偶数,这个循环会永远执行——因为数组元素的值没被修改,只要它是偶数,条件就一直为真,程序会反复把同一个偶数加到总和里,直接卡死。这里应该用if判断,只检查一次,符合条件就累加一次。 - 二维数组访问方式错误:你的函数参数是
int arr[](本质是一维指针),但你在函数里用了二维数组的语法arr[i][j],这在C++里是不合法的。正确的访问方式应该是用一维索引计算:arr[i * Columns + j],毕竟你传入的是&b[0][0](数组首元素的指针)。 - 缺少偶数计数变量:你的需求是计算偶数的平均值,但原代码只算了总和,没有统计偶数的数量,没法完成平均值计算。
main函数返回类型不规范:C++标准要求main函数必须返回int类型,void main()是非标准写法,会在部分编译器里报错。
修正后的完整代码
#include <iostream> #include <iomanip> using namespace std; // 同时计算偶数总和和数量,用引用参数传递计数 void calculateEvenStats(int arr[], int Rows, int Columns, int& sum, int& count) { sum = 0; count = 0; for (int i = 0; i < Rows; i++) { for (int j = 0; j < Columns; j++) { int current = arr[i * Columns + j]; if (current % 2 == 0) { // 把while改成if,避免无限循环 sum += current; count++; } } } } int main() { // 修正main的返回类型 const int rowCount = 4, colCount = 5; int b[rowCount][colCount] = { { 2, 5, 6, 7, 0 }, { 8, 6, 4, 7, 1 }, { 3, 6, 1, 9, 5 }, { 5, 6, 7, 3, 2 } }; // 打印原数组 for (int i = 0; i < rowCount; i++) { for (int j = 0; j < colCount; j++) cout << setw(6) << b[i][j]; cout << endl; } cout << endl; int evenSum, evenCount; calculateEvenStats(&b[0][0], rowCount, colCount, evenSum, evenCount); cout << "Sum of even numbers = " << evenSum << endl; if (evenCount > 0) { // 避免除以0的情况 double average = static_cast<double>(evenSum) / evenCount; cout << "Average of even numbers = " << fixed << setprecision(2) << average << endl; } else { cout << "There are no even numbers in the array." << endl; } return 0; // 标准main函数的返回值 }
代码说明
- 把原来的
sumOfEvenNumbers改成了calculateEvenStats,用引用参数sum和count来同时返回偶数总和和数量,这样就能计算平均值了。 - 把
while改成if,彻底解决无限循环问题。 - 统一用
arr[i * Columns + j]访问数组元素,匹配传入的一维指针类型。 - 增加了除以0的判断(如果数组里没有偶数的情况),避免程序崩溃。
- 修正了
main函数的返回类型,符合C++标准。
运行这段代码,你会得到正确的偶数总和和平均值:
2 5 6 7 0 8 6 4 7 1 3 6 1 9 5 5 6 7 3 2 Sum of even numbers = 46 Average of even numbers = 5.75
内容的提问来源于stack exchange,提问作者Maximko Payne
相关产品推荐
相关产品推荐

