【问题标题】:C++ if statement is not testing correctly [closed]C ++ if 语句未正确测试[关闭]
【发布时间】:2012-07-01 21:19:27
【问题描述】:

我正在尝试制作井字游戏,它可以在我可以插入 X 的范围内工作,但计算机只能插入一个 O。由于这是一个井字游戏,我需要计算机能够插入多个零。如果已经有一个值为 o 的变量,则每次运行此代码时,它都不会将另一个变量更改为值 o。我认为问题在于 if 语句。很抱歉没有明确说明我的问题。如果仍然没有意义,您可以编译我的其余代码。那么你可能会明白我的意思。

这里是the rest

这就是我认为的问题所在。

bool j=true ;
int lo=0;
string hi [9]={a,b,c,d,e,f,g,h,i};
while(j==true)
{
  if (lo>8)
  {
    j=false;
  }
  else if(hi[lo]!="x"&&hi[lo]!="o")
  {
    hi[lo]="o";
    j=false;
  }
  else
  {
    lo=lo+1;
    j=true;
  }
}

【问题讨论】:

  • 您的问题是什么?您的代码专门用于插入一个“o”并退出(立即将j 设置为false)。那有什么问题呢? “if 语句未正确测试”是什么意思?
  • 代码第一次工作,但是当有一个 o 已经存储在其中一个值中时,它不会输入第二个 o。这就是为什么我说它没有正确测试。
  • 说真的,我不介意这会被否决,但至少你可以做的就是从链接中编译代码,看看我对你自己的意思。
  • @user1108980 但是代码做了它看起来的样子:在数组中第一个没有“o”或“x”的位置放置一个“o”。为什么你认为它会做其他事情?很可能,错误出现在其他地方,例如将字符串数组复制回单个字符串的代码中。

标签: c++ if-statement console tic-tac-toe


【解决方案1】:

如果我可以重写你的代码:

for (lo = 0; lo < 9; lo++){
  if (hi[lo] == " "){
    hi[lo] = "o";
    break;
  }
}

所以你是对的,它插入了一个“o”。

问题是什么?

编辑:由于您正在尝试编写井字游戏,让我建议一些整体伪代码:

repeat
  ask user where they want to place an "x" (i.e. get a number from 0 to 8)
  if that square is not blank, say so and ask again
  else put the "x" in the square
  If this completes a row, column, or diagonal, exit saying "You win!"
-> enter the loop here if you are making the first move
  then find out where to put an "o". You do this by looking at all unoccupied squares.
  for each unoccupied square
    look at the row, column, and diagonal it is on
    if putting an "o" there would make you the winner, give it a really high score
    if putting an "o" there would block the user from winning, give it a high score
    if putting an "o" there would mean that you could win on the following move, give it a medium score
    Otherwise give it a score that is the number of rows, columns, and diagonals it could possibly tie up
    end for each
  Then put the "o" on the highest-scored square (or one of the highest-scored squares if there are more than one)
  If you completed a row, column, or diagonal, exit saying "I win!".
  If you can't find a square to mark, exit saying "I give up".
end repeat

我确信有比这更短的版本。 这只是我的想法。

【讨论】:

  • 对于我第一次编写它的混乱代码感到抱歉。然后我被难住了,所以我尝试用其他几种方式重写它。
猜你喜欢
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
相关资源
最近更新 更多