以下是一个使用 C++ 编写的猜数字游戏的示例代码:

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

int main() {
    srand(time(0)); // 设置随机数种子
    int secretNumber = rand() % 100 + 1; // 生成 1 到 100 的随机数
    int guess;
    int attempts = 0;

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

    do {
        std::cout << '请输入你猜测的数字(1-100): ';
        std::cin >> guess;
        attempts++;

        if (guess > secretNumber) {
            std::cout << '猜测的数字太大了!' << std::endl;
        } else if (guess < secretNumber) {
            std::cout << '猜测的数字太小了!' << std::endl;
        } else {
            std::cout << '恭喜你猜对了!' << std::endl;
            std::cout << '你猜测了 ' << attempts << ' 次。' << std::endl;
        }
    } while (guess != secretNumber);

    return 0;
}

这个小游戏会随机生成一个 1 到 100 之间的数字,然后玩家需要根据提示输入猜测的数字,直到猜对为止。游戏会记录玩家猜测的次数并在猜对时显示出来。

C++ 猜数字游戏代码示例 - 初学者指南

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

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