以下是一个简单的 C++ 猜数字游戏代码示例:

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

using namespace std;

int main() {
    srand(time(0)); // 使用当前时间作为随机数种子

    int number = rand() % 100 + 1; // 生成 1 到 100 之间的随机数
    int guess;
    int tries = 0;

    cout << '猜数游戏开始!' << endl;

    do {
        cout << '请输入你的猜测: ';
        cin >> guess;
        tries++;

        if (guess > number) {
            cout << '猜大了,请继续猜测!' << endl;
        } else if (guess < number) {
            cout << '猜小了,请继续猜测!' << endl;
        } else {
            cout << '恭喜你!猜对了!' << endl;
            cout << '你一共猜了 ' << tries << ' 次。' << endl;
        }
    } while (guess != number);

    return 0;
}

这个程序是一个猜数字游戏,玩家需要猜一个 1 到 100 之间的随机数。程序会根据玩家的猜测给出相应的提示,直到玩家猜对为止。程序还会记录玩家猜的次数,并在玩家猜对后显示出来。

C++ 猜数字游戏代码示例 - 简单易懂

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

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