这个代码是一个很好的解决方案,可以随机化二维数组并写出所有数据 屏幕上的符号?如果您有更好的提示或解决方案,请告诉我。
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");
}
答案 0 :(得分:2)
您不需要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");
}
但请注意,这不是很随机,因为您只从三个不同的行中选择。
答案 1 :(得分:0)
除了最后一个应该是:
if(slumpnr == 2) // 2 instead of 3
一切都很好看。您正确地初始化随机序列(注意只在启动时执行一次),因此您应该获得计算机可以做的最佳随机序列。