求助:如何用函数实现两个二维数组相加并存储显示到第三个数组?
Fixing 2D Array Element-Wise Addition in C
Your code is calculating the total sum of all elements from both arrays instead of performing element-wise addition. Here's how to fix it:
Key Issues in Original Code
- The
doAddfunction accumulates a single total sum instead of storing each element-wise sum in the third arrayc. - Duplicate display functions that don’t format arrays into rows for readability.
- Main function prints the total sum instead of the result array.
Corrected Code
#include <stdio.h> // Reusable function to display any 3x3 array with a label void displayArray(int arr[3][3], const char* label) { printf("\n %s: \n", label); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf(" %d ", arr[i][j]); } printf("\n"); // New line after each row for clarity } } // Perform element-wise addition and store result in c void doAdd(int a[3][3], int b[3][3], int c[3][3]) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { c[i][j] = a[i][j] + b[i][j]; // Assign sum to corresponding element in c } } } int main() { int a[3][3]; int b[3][3]; int c[3][3]; // Input elements for first array for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("Enter element for a[%d][%d]: ", i, j); scanf("%d", &a[i][j]); } } printf("\n****************************\n"); // Input elements for second array for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("Enter element for b[%d][%d]: ", i, j); scanf("%d", &b[i][j]); } } // Show input arrays displayArray(a, "1st Array"); displayArray(b, "2nd Array"); // Calculate element-wise sums doAdd(a, b, c); // Display the result array displayArray(c, "Addition of two Arrays"); return 0; }
What Changed
- Reusable Display: Replaced duplicate display functions with one
displayArraythat works for any 3x3 array and formats rows properly. - Fixed Addition:
doAddnow fillscwith each pair of corresponding elements added together, instead of calculating a total sum. - Clearer Input: Added array and index references to input prompts so users know exactly what they’re entering.
- Display Result: Instead of printing a single sum, we show the entire result array in a readable grid.
内容的提问来源于stack exchange,提问作者Rahul Deshmukh
相关产品推荐
相关产品推荐

