无法使用for循环填充10x10数组

时间:2019-01-12 07:30:51

标签: c++ arrays loops

我正试图让该程序打印出10 x 10的一组从4 x 4数组中随机获取的值。

所有行的长度应为10;由于某些原因,有些行已经有7和10个条目。其他时候,他们每个人只有10个,但往往不是一个或多个都是空的。只是想弄清楚如何使此东西每次打印10行和列。编码新手。


iostream, cstdlib, string, math.h, time.h

using namespace std;

int main()
{

srand(time(NULL));

string worldMap[10][10];

string envir[4][4] = { {"S1", "S2", "S3", "S4"}, {"P1", "P2", "P3", "P4"},
               {"F1", "F2", "F3", "F4"}, {"D1", "D2", "D3", "D4"} };

for (int i = 0; i < 10; i++)
{   
    for (int j = 0; j < 10; j++)
    {

        int cat = rand()%4+1;
        int subcat = rand()%4+1;
        worldMap[i][j] = envir[cat][subcat];
        cout<<worldMap[i][j];
    }
    cout<<endl;
}
 return 0;
}

1 个答案:

答案 0 :(得分:5)

C ++使用基于零的索引,您编写了rand()%4+1,它创建了1-4范围内的数字并将其用作索引。

相反,它应该只是rand()%4