以下是一个简单的 C++ 控制台游戏,你可以根据需求进行修改和扩展:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    srand(time(NULL)); // 用当前时间初始化随机种子

    int targetNumber = rand() % 100 + 1; // 生成 1-100 之间的随机数
    int guess;
    int attempts = 0;

    cout << '欢迎来到猜数字游戏!' << endl;

    while (true) {
        cout << '请输入一个 1-100 之间的整数:';
        cin >> guess;

        attempts++;

        if (guess < targetNumber) {
            cout << '太小了!' << endl;
        } else if (guess > targetNumber) {
            cout << '太大了!' << endl;
        } else {
            cout << '恭喜你猜对了!' << endl;
            cout << '你共猜了' << attempts << '次。' << endl;
            break;
        }
    }

    return 0;
}

这个小游戏会生成一个 1-100 之间的随机数,然后要求玩家猜这个数字。每次玩家猜测后,程序会告诉玩家猜的数字是太大还是太小,直到猜对为止。最后会显示玩家猜了多少次才猜对。


原文地址: https://www.cveoy.top/t/topic/p3dC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录