【问题标题】:Function auto-assigns values in my matrix函数在我的矩阵中自动分配值
【发布时间】:2018-03-14 04:27:50
【问题描述】:

我正在尝试制作类似 2048 的游戏,但遇到了问题。

    #include <iostream>
    #include <conio.h>
    #include <windows.h>
    #include <time.h>
    using namespace std;

    void random();
    void randomCoord();

    int gt[3][3];
    int r,coordi,coordj;

    void initiate()
    {
        for(int i=0;i<=3;i++)
            for(int j=0;j<=3;j++)
                gt[i][j]=0;
        random();
    //  randomCoord();
    //  gt[coordi][coordj]=r;
    //  randomN();
    //  randomCoord();
    //  gt[coordi][coordj]=r;
        for(int i=0;i<=3;i++)
        {
            cout<<endl;
            for(int j=0;j<=3;j++)
                cout<<gt[i][j]<<" ";
        }
    }

    void random()
    {
        srand (time(NULL));
        do
            {
                r = rand() % 4 + 2;
                if(r==2 || r==4)
                    break;
            }
        while(1);
    }
    void randomCoord()
    {
        srand (time(NULL));
        coordi = rand() % 4;
        coordj = rand() % 4;
    }

    int main()
    {
        initiate();

        return 0;
    }

我希望当我在屏幕上打印矩阵时得到一个全为零的矩阵......但由于某种原因,gt[2][3]gt[3][0] 的值得到了r 的值。我不明白为什么。

感谢您的帮助!

【问题讨论】:

标签: c++ c++11 matrix multidimensional-array


【解决方案1】:

如果你想写gt[2][3]gt[3][0],你的gt必须是

int gt[4][4];

如果您的gtgt[3][3],当您在位置3(对于第一个或第二个索引)访问时,您(据我所知)处于未定义行为。

【讨论】:

  • 哦……现在我明白了!真是个愚蠢的错误。谢谢你的帮助。
猜你喜欢
  • 2015-11-10
  • 2013-04-06
  • 2017-10-12
  • 2021-10-13
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
相关资源
最近更新 更多