c++编写一个函数求二维数组中周边元素之和
作者:野牛程序员:2023-11-30 11:56:18 C++阅读 2581
c++编写一个函数求二维数组中周边元素之和
#include <iostream> int calculateEdgeSum(const int array[][5], int rows, int cols) { int sum = 0; // 计算上边缘 for (int j = 0; j < cols; ++j) { sum += array[0][j]; } // 计算下边缘 for (int j = 0; j < cols; ++j) { sum += array[rows - 1][j]; } // 计算左边缘 for (int i = 1; i < rows - 1; ++i) { sum += array[i][0]; } // 计算右边缘 for (int i = 1; i < rows - 1; ++i) { sum += array[i][cols - 1]; } return sum; } int main() { const int rows = 3; const int cols = 5; int myArray[rows][cols] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}}; int result = calculateEdgeSum(myArray, rows, cols); std::cout << "边缘元素之和: " << result << std::endl; return 0; }
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892