C++ 用字符随机化二维数组?
这段代码是一个很好的解决方案,可以将二维数组随机化并写出所有 屏幕上的符号?如果你有更好的建议或解决方案,请告诉我C++ 用字符随机化二维数组?,c++,arrays,C++,Arrays,这段代码是一个很好的解决方案,可以将二维数组随机化并写出所有 屏幕上的符号?如果你有更好的建议或解决方案,请告诉我 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 <<
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");
}
int;
srand(时间(0));
字符游戏[3][3]={'O','X','A'},{'X','A','X'},{'A','O','O'};
对于(int i=0;i<5;i++)
{
slamenr=rand()%3;
如果(n=1)
{
cout除非最后一个是:
if(slumpnr == 2) // 2 instead of 3
一切看起来都正常。您正在正确初始化随机序列(注意仅在启动时执行一次),因此您应该获得计算机可以执行的最佳随机序列。您不需要if/else链。只需将随机变量用作数组的索引:
int r = rand() % 3;
cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
cout << "___|___|___\n";
int r=rand()%3;
即使是发布了上一个问题的用户,也不可能重复相同的内容。@Nelly-您可以编辑上一个问题。.好的,对不起,我是这个网站的新用户,但现在我知道了。这不是最好的。例如,在16位机器上,(rand()%3)
稍微有点偏向于返回<代码> 0代码>代码。这个偏倚只有0.005%左右!你能帮我把这些代码拿到我的代码中吗?因为我不懂如何把我的代码放进去。你有MSN吗?还是因为什么?因为我真的需要完成我的代码,我很喜欢C++。谢天谢地!@耐莉:注意我更喜欢。。。
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";
#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");
}