【发布时间】:2019-03-16 20:10:47
【问题描述】:
我尝试编写一个 c++ 程序,但每次都得到错误的结果。
每当我分别指定 x 和 y 坐标 2 和 3 时,它会将两个元素指定为“X”,而不仅仅是一个。我现在已经试过很多次了。
代码:
#include<iostream.h>
#include<conio.h>
void reset(char a[2][2])
{
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
a[i][j] = '_';
}
void dispmat(char a[2][2])
{
for (int k = 0; k < 3; k++)
{
for(int l = 0; l < 3; l++)
cout << a[k][l] << '\t';
cout << endl;
}
}
void getcoordinates(int &x, int &y)
{
cout << "Enter the row: "<< endl;
cin >> x;
cout << "Enter the column:" << endl;
cin >> y;
x--;
y--;
}
void main()
{
clrscr();
char a[2][2],yon = 'y';
int t = 2,x,y, flag = 0;
do
{
reset(a);
for(int h = 0; h < 9; h++) // max no. of cells to be filled = 9
{
clrscr();
dispmat(a); // displays matrix
if(t++%2 == 0) // X's turn
{
cout << "It is X \'s chance now" << endl;
getcoordinates(x,y);
a[x][y] = 'x';
for(int m = 0; m < 3; m++)
//if any one condition is true, x is declared the winner
if((a[m][0] == a[m][1] && a[m][1] == a[m][2] && a[m][2] == 'x')||(a[0][m] == a[1][m]&&a[1][m] == a[2][m] && a[2][m] == 'x')||(a[0][0] == a[1][1]&&a[1][1] == a[2][2] && a[2][2] == 'x')||(a[2][0] == a[1][1]&&a[1][1] == a[0][2] && a[0][2] == 'x'))
{
flag = -1; //if flag = 1, x wins
//if flag = -1, 0 wins
// if flag = 0, its a draw
break;
}
if (flag == -1||flag == 1)
break;
}
else // 0's turn
{
cout << "It is 0 \'s chance now" << endl;
getcoordinates(x,y);
a[x][y] = '0';
for(int n = 0; n < 3; n++)
if((a[n][0] == a[n][1] && a[n][1] == a[n][2] && a[n][2] == '0')||(a[0][n] == a[1][n]&&a[1][n] == a[2][n] && a[2][n] == '0')||(a[0][0] == a[1][1]&&a[1][1] == a[2][2] && a[2][2] == '0')||(a[2][0] == a[1][1]&&a[1][1] == a[0][2] && a[0][2] == '0'))
{
flag = 1;
break;
}
if(flag == 1)
break;
}
}
if(flag == 1)
cout << "Winner is 0!" << endl;
else if(flag == -1)
cout << "Winner is X!" << endl;
else
cout << "It is a draw!" << endl;
cout << "Do you want to continue?" << endl;
cin >> yon;
} while(yon == 'y' || yon == 'Y');
getch();
}
【问题讨论】:
-
无关:如果您可以选择使用的编译器,请不要使用 Turbo C++。那个吸盘已经过时了几十年。有许多免费的替代品,例如 Visual Studio 社区版,它们不会过时 30 年。
-
我在 C++ 中不是那么坚定 - 但如果你愿意,你不应该为你的数组维度“char a[3][3]”而不是“char a[2][2]”有 3x3 元素?
-
我今天很懒。当您使用调试器时,哪些语句导致了问题?请使用信息编辑您的帖子,并说明预期变量值是什么以及实际值。
-
顺便说一句,
main函数返回一个int给操作系统。总是。 -
@ThomasMatthews 在这里,main 的返回类型是 void 因此不需要返回语句......但是在这个社区和像你这样的人的帮助下,我能够解决我的小错误...