gpt4 book ai didi

c++ - 用字符随机化一个二维数组?

转载 作者:行者123 更新时间:2023-11-28 03:54:52 25 4
gpt4 key购买 nike

这段代码是一个很好的解决方案,可以随机化一个二维数组并写出所有的屏幕上的符号?如果您有更好的提示或解决方案,请告诉我。

 int slumpnr;
srand( time(0) );
char game[3][3] = {{'O','X','A'}, {'X','A','X'}, {'A','O','O'}};

for(int i = 0 ; i < 5 ; i++)
{
slumpnr = rand()%3;
if(slumpnr == 1)
{
cout << " " <<game[0][0] << " | " << game[0][1] << " | " << game[0][2] << "\n";
cout << "___|___|___\n";
}
else if(slumpnr == 0)
{
cout << " " << game[1][0] << " | " << game[1][1] << " | " << game[1][2] << "\n";
cout << "___|___|___\n";
}
else if(slumpnr == 3)
{
cout << " " << game[2][0] << " | " << game[2][1] << " | " << game[2][2] << "\n";
cout << "___|___|___\n";
}
}
system("pause");
}

最佳答案

您不需要 if/else 链。只需使用随机变量作为数组的索引:

int r = rand() % 3;
cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
cout << "___|___|___\n";

哦,我刚刚注意到你有一个从 1 到 0 和从 0 到 1 的奇怪映射。如果真的有必要(无论出于何种原因),我会像这样实现它:

static const int mapping[] = {1, 0, 2};
int r = mapping[rand() % 3];
cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
cout << "___|___|___\n";

不,我没有 MSN 或其他东西,但这里有一个完整的程序可以帮助你。

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
srand(time(0));
char game[3][3] = {{'O','X','A'}, {'X','A','X'}, {'A','O','O'}};

for (int i = 0; i < 5; ++i)
{
int r = rand() % 3;
std::cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
std::cout << "___|___|___\n";
}
system("pause");
}

但是请注意,这不是很随机,因为您只能从三个不同的可能行中进行选择。

关于c++ - 用字符随机化一个二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4004519/

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