You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何用函数实现两个二维数组相加并存储显示到第三个数组?

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 doAdd function accumulates a single total sum instead of storing each element-wise sum in the third array c.
  • 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

  1. Reusable Display: Replaced duplicate display functions with one displayArray that works for any 3x3 array and formats rows properly.
  2. Fixed Addition: doAdd now fills c with each pair of corresponding elements added together, instead of calculating a total sum.
  3. Clearer Input: Added array and index references to input prompts so users know exactly what they’re entering.
  4. Display Result: Instead of printing a single sum, we show the entire result array in a readable grid.

内容的提问来源于stack exchange,提问作者Rahul Deshmukh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 21:12:49