gpt4 book ai didi

c++ - 在数组中存储整数存储随机值

转载 作者:行者123 更新时间:2023-11-28 04:41:24 25 4
gpt4 key购买 nike

我正在用 C++(我最熟悉的语言)编写我自己的扫雷游戏,当我在二维数组中存储一个常量时,它有时会存储一个随机值。

这是我的代码:

using namespace std;

Table::Table() {
tiles[16][16] = {0};
covers[16][16] ={1};


}//stores position of mines, covers, and values

//places mines on the board
void Table::placemines() {
int minecount=0;
int i = rand()%15;
int j = rand()%15;
while(minecount<40){
if (tiles[i][j] == 0) {
tiles[i][j] = -10;
minecount++;
} else {}
i = rand()%15;
j = rand()%15;
}
}

和我的 main.cpp 来显示值

using namespace std;

int main() {
Table newtable = Table();
newtable.placemines(6, 7);
for (int j = 0; j < 16; j++) {
for (int i = 0; i < 16; i++) {
cout << newtable.tiles[i][j] << ' ';

}
cout << '\n';
}
}

和输出

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 -10 -10 -10 0 0 1 -10 0 0
0 0 0 0 0 0 0 -10 0 -10 -10 0 -10 0 0 0
0 0 0 0 0 -10 0 0 0 -10 -10 0 -10 0 0 0
-10 0 0 -10 -10 0 0 -10 -10 0 0 0 0 -10 0 0
-10 0 -10 0 0 -10 0 0 0 0 0 0 0 -10 0 0
0 0 0 0 0 0 0 0 -10 -10 0 1920169263 0 -10 0 0
0 0 -10 0 0 0 0 0 0 -10 -10 1651076143 0 0 0 0
0 0 0 0 0 0 0 0 -10 -10 0 1819894831 -10 0 0 0
0 0 0 0 0 0 0 0 0 0 0 100 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 -10 0 0 0 0
0 0 0 0 0 0 0 -10 0 -10 0 32 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
-10 0 0 -10 0 0 0 0 0 0 -10 2 0 0 0 0
-10 0 0 0 0 -10 0 0 0 -10 0 4 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0

谁能告诉我这是怎么回事?谢谢!

最佳答案

太多代码缺失,没有声明,没有placemines()代码

这里有错误:

tiles[16][16] = {0};

此语句将索引为 16 和 16 的数组的某些元素设置为 0。如果您的数组定义为 type tiles[16][16] 这意味着您写入 Abyss 并导致 UB (因为数组的最后一个元素是 tiles[15][15])。

如果必须初始化数组,请使用std::fill http://en.cppreference.com/w/cpp/algorithm/fill .对于零初始化,这是可行的:

Table::Table() : tiles{0} {

另一个可能的错误:

int i = rand()%15;

您必须使用数组的大小来正确覆盖范围。

附言。避免 using namespace std; 在全局范围内,pleeeese。

关于c++ - 在数组中存储整数存储随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50122469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com