我需要有关数组的帮助

时间:2019-10-26 14:06:34

标签: c

程序说明:

1/2/3

2 3 5

2 9 4

2 5 7

如果我在上面写上1张,给我2 + 9 + 7

如果我写2个,给我5 + 9 + 2

如果我在上面写3则给我(2 + 9 + 7)-(5 + 9 + 2)

(但让我们警惕的是:

*检测到堆栈粉碎* :未知终止 中止(核心已弃用)

    #include <stdio.h>
    #include <math.h>

    int main()
    {
        int whatUDo;
        int square[2][2];
        int counter1 = 0, counter2 = 0, counter3 = 0;
        int threeTime = 3;
        scanf("%d", &whatUDo);

        while (counter1 < 3)
        {
            scanf("%d", &square[0][counter1]);
            counter1++;
        }
        while (counter2 < 3)
        {
            scanf("%d", &square[1][counter2]);
            counter2++;
        }
        while (counter3 < 3)
        {
            scanf("%d", &square[2][counter3]);
            counter3++;
        }
        int first = square[0][0] + square[1][1] + square[2][2];
        int second = square[0][2] + square[1][1] + square[2][0];
        int third = first - second;

        if (whatUDo == 1)
        {
            printf("%d", first);
        }
        else if (whatUDo == 2)
        {
            printf("%d", second);
        }
        else if (whatUDo == 3)
        {
            printf("%d", third);
        }
        return 0;
    }

1 个答案:

答案 0 :(得分:0)

TL; DR

您的数组大小错误。


对于您提供的代码,必须将数组声明为

int square[3][3];

因为要处理的边界分别来自0..2和0..2。声明数组时指定的数字是大小,而不是允许的最大索引。

以其他方式,如果您声明:

int myarray[5];

您可以从0到4访问数组中的项目,并且您的数组可以通过索引0、1、2、3和4访问5个项目。