0

我的程序是用来玩牙签游戏的,我已经坚持了一段时间。目标是让计算机从 23 根牙签中取出牙签,而人类也会这样做。到目前为止,我的逻辑似乎不起作用。玩家可以拔出一定数量的牙签,它被从总数中取出,但是当计算机取出牙签时,它只需要一根牙签。我让程序说还剩多少,计算机取出多少。看来,既然计算机总是拿出一根牙签,那么栈中总还有一根牙签,这显然在数学上是不正确的。

#include <iostream>
#include <conio.h>
#include <cmath>

using namespace std;

int main()
{

int toothpicks = 23, human, comp;


cout<<"TOOTHPICKS!!!!!" <<endl;

while (toothpicks >0)
{
    cout<<"Human, take your toothpick(s)! But only between 1 and 3 toothpick(s), Thanks! ";
    cin>>human;

    toothpicks = toothpicks - human;
    cout<<toothpicks <<" toothpick(s) remaining" <<endl;

    if (toothpicks = 0)
    {
        cout<<"Human! You have prevailed!"<<endl;
        break;
    }

    if (toothpicks >4)
    {
        comp = 4 - human;   
        cout<<"The computer took " <<comp <<" toothpick(s)" <<endl;
    }
    else if (toothpicks = 2)
    {
        comp = 1;
        cout<<"The computer took " <<comp <<" toothpick(s)" <<endl;
    }
    else if (toothpicks = 3)
    {
        comp = 2;
        cout<<"The computer took " <<comp <<" toothpick(s)" <<endl;
    }
    else if (toothpicks = 4)
    {
        comp = 3;
        cout<<"The computer took " <<comp <<" toothpick(s)" <<endl;
    }
    else if (toothpicks = 1)
    {
        comp = 1;
        cout<<"The computer took " <<comp <<" toothpick(s)" <<endl;
    }

    toothpicks = toothpicks - comp;
    cout<<toothpicks <<" toothpick(s) remaining";

    if (toothpicks = 0)
    {
        cout<<"The computer has prevailed!"<<endl;
        break;
    }

}

_getche();
return 0;
4

2 回答 2

3

使用 == 进行比较,而不是 =(执行赋值)。

于 2012-10-12T21:47:15.460 回答
0

这可能是您的实际代码吗?您只是忘记了在 C++ 中=设置值并==进行比较!!在行中if (toothpicks = 0),您将值重置toothpicks为 0,并且由于 C++ 认为 0 为 false,它将忽略此行并继续其他行,如果它们都有相同的问题!所以你应该替换===并说if (toothpicks == 0)else if (toothpicks == 2)

于 2012-10-12T21:52:25.983 回答