c++ NIM游戏逻辑错误

C++ NIM game logical error

本文关键字:错误 游戏 NIM c++      更新时间:2023-10-16

**显示不正常,主板内实现时显示不正常

这是NIM游戏的更新代码<<获胜者功能和显示功能不能正常工作**我需要帮助弄清楚如何让显示功能正常工作,请。

class cboard{
    private:
int sticks;
bool player;
    public:
//default constructor
cboard(){sticks=10;}
//constructor with parameter given
cboard(int x){sticks=x;}
//stick set
void setstick(int m){sticks-=m;}
//display stick getter
int get_sticks(){return sticks;}
//display function, a.k.a baord getter
void displaycboard ()
{for (int i=sticks; i>0; i--)
    {cout<<"| ";}
    cout<<endl;}
};

您的displaycboard()直接修改类成员变量sticks,在第一个displaycboard()之后将其减少为0。下次调用displaycboard()时,成员变量sticks为0,这意味着没有什么要打印的。

您的问题在于displaycboard()for循环需要更改一个非sticks的变量。

将代码改为

for (int i = sticks; i > 0; i--)
{
...
}

,它工作得很好。它仍然输出两行,因为在循环中被反复调用(因为循环迭代,并且在第一次循环结束时调用相同数量的棍棒,第二个循环开始)。

编辑:参考关于您的goto BAD的评论,您可以将其替换为

int s = 0;
while (s <= 2)
{
    cout << "How many... greater than 2" << endl;
    cin >> s;
}

第二次编辑:您的评论反映出您知道这是不安全的,但您可以使用stringstream (#include <sstream>)和

处理非int值。
std::string instring;
    while (s <= 2)
    {
    cout<<"How many sticks would you like to play with this game (Greater than 2): ";
    getline(cin, instring);
    stringstream(instring) >> s;
    }

这将允许您输入1.25之类的东西,并让程序要求一个新值,或5.25,并让它玩5棒。请注意,5.99仍然给出5棒…