C++ 牙签计划

C++ Toothpicks program

本文关键字:计划 C++      更新时间:2023-10-16

我的程序是为了玩牙签游戏而制作的,我已经坚持了一段时间了。目标是让计算机从一堆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;

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

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