[英]'+=: Command not found' when trying to add a value to an array - Shell Script
[英]Trying to search for a value of an array and change the value when found
我刚刚开始 c 编程语言,并正在尝试创建井字游戏。 我在互联网上找到了很多我一直在关注和修改的信息和教程。 目前我有教程中的代码,可以根据用户选择的方块更新网格。 但我想把它改成循环。 但是,我无法使循环正常工作。 我错过了什么或做错了什么......或者它甚至可以这样做。 这是我的代码:
if(player % 2)
{
player = 1;
}
else
{
player = 2;
}
printf("Please enter the number of the square to place your marker ");
printf("Player %d : ", player);
scanf("%d", &move);
if(player == 1)//get the right marker
{
marker = 'O';
}
else
{
marker = 'X';
}
if (move == 1 && grid_sq[0] == '1')
{
grid_sq[0] = marker;
}
else if (move == 2 && grid_sq[1] == '2')
{
grid_sq[1] = marker;
}
else if (move == 3 && grid_sq[2] == '3')
{
grid_sq[2] = marker;
}
else if (move == 4 && grid_sq[3] == '4')
{
grid_sq[3] = marker;
}
else if (move == 5 && grid_sq[4] == '5')
{
grid_sq[4] = marker;
}
else if (move == 6 && grid_sq[5] == '6')
{
grid_sq[5] = marker;
}
else if (move == 7 && grid_sq[6] == '7')
{
grid_sq[6] = marker;
}
else if (move == 8 && grid_sq[7] == '8')
{
grid_sq[7] = marker;
}
else if (move == 9 && grid_sq[8] == '9')
{
grid_sq[8] = marker;
}
else
{
printf("\t\t\tMove is not valid! Try again. ");
getch();
}
我想把它变成一个循环,我一直在尝试的循环是:
for (i=0; 1<9; i++)
{
if(grid_sq[i]==move)
{
grid_sq[i]=marker
}
}
您的for
循环条件中有错字, 1<9
应该是i<9
。
但是不需要所有这些if
语句或循环。 您可以将move
转换为数组索引。
if (move >= 1 && move <= 9) {
if (grid_sq[move-1] == move + '0') {
grid_sq[move-1] = marker;
} else {
printf("That square is already taken, try again\n");
getch();
}
} else {
printf("Square must be between 1 and 9, try again\n");
getch();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.