用C++构建一个23人的牙签游戏

Building a Toothpick Game of 23 in C++

本文关键字:23人 游戏 一个 构建 C++      更新时间:2023-10-16

我正在用C++构建一个23岁的牙签游戏,作为编程课程的家庭作业。我几乎完成了代码,输出看起来与我要遵循的完全一样。

我应该在代码中使用一个函数,但我不知道如何使用这个函数。程序中的所有内容都正常工作,除了函数返回0,0是输出的最后一行,这一行与我应该遵循的输出不相同。所以也许有人可以帮我找出我该怎么做。

#include <iostream>
using namespace std;
int computerMove(int numPicksLeft, int humanNumber);
int main()
{
    int a, z=0, y=0;
    a = computerMove(z, y);
    cout << a;

    return 0;
}
int computerMove(int numPicksLeft, int humanNumber) {
    int number_left=23, n, cpu_turn;
    do{
        cout << "There are " << number_left << " toothpicks left. Pick 1, 2 or 3 toothpicks: ";
        cin >> n;

        if (n <= 3)
        {
            number_left -= n;
            if (number_left > 4)
            {
                cpu_turn = (4 - n); // þar sem n er fjöldi tannstöngla dregnir af notanda.
                cout << "I pick " << cpu_turn << " toothpicks" << endl;
                number_left -= cpu_turn;
            }
            else if (number_left == 2)
            {
                cpu_turn = 1;
                cout << "I pick " << cpu_turn << " toothpicks" << endl;
                number_left -= cpu_turn;
            }
            else if (number_left == 3)
            {
                cpu_turn = 2;
                cout << "I pick " << cpu_turn << " toothpicks" << endl;
                number_left -= cpu_turn;
            }
            else if (number_left == 4)
            {
                cpu_turn = 3;
                cout << "I pick " << cpu_turn << " toothpicks" << endl;
                number_left -= cpu_turn;
            }
            else if (number_left == 1)
            {
                cpu_turn = 1;
                cout << "I pick " << cpu_turn << " toothpicks" << endl;
                cout << "You won!" << endl;
                number_left -= cpu_turn;
            }
            else if (number_left == 0)
            {
                cpu_turn = 0;
                cout << "I pick " << cpu_turn << " toothpicks" << endl;
                cout << "I won!" << endl;
            }
        }
        else
            cout << "Invalid input. Try again." << endl;
    } while (number_left > 0);
    return 0;
}

我总是在最后一行得到这个0,我不想那样。所以我的问题是,我该如何使用这个函数,这样它就不会是这样了?

函数签名表示函数的返回类型为整数(int)。如果函数到达您在主函数中指定并打印的末尾,则函数本身最终将返回0。如果你对函数的结果不感兴趣,为什么要让它返回一些东西?

您可以将返回类型更改为void,而不返回/分配任何内容,0将被忽略。

void computerMove(int numPicksLeft, int humanNumber) {
    // Your code
    // No return statement!
}

比如这样的东西。

作为旁注,避免using namespace std;