简体   繁体   English

添加数组的结果是错误的

[英]The result is wrong in add array

Each row without last row is person's score at math, eng, kor, science.没有最后一行的每一行是人在数学、英语、韩语、科学方面的分数。

I mean that arr[0][0] = person 1's math score:我的意思是arr[0][0] = 人 1 的数学分数:

arr[0][1] = person 1's eng score
arr[0][2] = person 1's kor score
arr[0][3] = person 1's science score
arr[0][4] = person 1's sum at each subject score
and arr[4][0] = sum at person 1,2,3,4's math score

and this code is run at vscode in mac这段代码在 mac 中的 vscode 上运行

#include <stdio.h>

int main(void)
{
    long i,j;
    int arr[5][5];

    printf("성적관리 프로그램 입니다.\n");
    for(i=0; i<4; i++)
    {
        for(j=0; j<4; j++)
        {
            switch (j)
            {
                case 0:
                    printf("국어 점수를 입력해 주세요: \n");
                    scanf("%d",&arr[i][j]);
                    break;
                case 1:
                    printf("영어 점수를 입력해 주세요: \n");
                    scanf("%d",&arr[i][j]);
                    break;
                case 2:
                    printf("수학 점수를 입력해 주세요: \n");
                    scanf("%d",&arr[i][j]);
                    break;
                case 3:
                    printf("국사 점수를 입력해 주세요: \n");
                    scanf("%d",&arr[i][j]);
                    break;
                default:
                    printf("오류 발생");
            }
            
        }
    }
    printf("개인 별 총점을 구하겠습니다.\n");
    for(i=0; i<4; i++)
    {
        for(j=0; j<4; j++)
        {
            arr[i][4] += arr[i][j];
        }
    }
    printf("과목 별 총점을 구하겠습니다.\n");
    
    for(i=0; i<4; i++)
    {
        for(j=0; j<4; j++)
        {
            arr[4][i] += arr[j][i];
        }
    }

    for(i=0; i<4; i++)
    {
        arr[4][4] += arr[4][i];
    }
    
    for(i=0; i<5; i++)
    {
        for(j=0; j<5; j++)
        {
            printf("%3d ", arr[i][j]);
        }
        printf("\n");
    }
    return 0;

}

The result is:结果是:

  1   2   3   4  10 
  1   2   3   4  10 
  1   2   3   4  11 
  1   2   3   4 1874065002 
  5 6040476 708575245 2898508 71751423

Your problem is that you aren't initializing the array elements to 0, so there are reminders in memory that not reset to 0, consider doing this after the array declaration:您的问题是您没有将数组元素初始化为 0,因此内存中有未重置为 0 的提醒,请考虑在数组声明后执行此操作:

for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        arr[i][j] = 0;
    }
}

or the {} shortcut at definition:或定义中的 {} 快捷方式:

int arr[5][5] = {};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM