Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++小游戏编程代码

作者:傲世,小狂徒   发布日期:2025-06-16   浏览:87

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

using namespace std;

// 定义一个猜数字游戏
void guessNumberGame() {
    // 初始化随机数种子
    srand(static_cast<unsigned int>(time(0)));

    // 生成1到100之间的随机数
    int secretNumber = rand() % 100 + 1;
    int userGuess = 0;
    int attempts = 0;

    cout << "欢迎来到猜数字游戏!" << endl;
    cout << "我已经想好了一个1到100之间的数字。" << endl;

    // 游戏主循环
    while (userGuess != secretNumber) {
        cout << "请输入你的猜测: ";
        cin >> userGuess;
        attempts++;

        if (userGuess > secretNumber) {
            cout << "太大了!再试一次。" << endl;
        } else if (userGuess < secretNumber) {
            cout << "太小了!再试一次。" << endl;
        } else {
            cout << "恭喜你,猜对了!你一共尝试了 " << attempts << " 次。" << endl;
        }
    }
}

int main() {
    guessNumberGame();
    return 0;
}

解释说明:

  1. 头文件#include <iostream>, #include <cstdlib>, #include <ctime> 引入了标准输入输出、随机数生成和时间相关的库。
  2. 命名空间using namespace std; 简化了标准库的使用,无需每次调用时都加前缀 std::
  3. 函数定义guessNumberGame() 是游戏的核心逻辑,负责生成随机数并处理用户的输入。
  4. 随机数生成srand(static_cast<unsigned int>(time(0))); 初始化随机数种子,确保每次运行程序时生成不同的随机数。
  5. 游戏循环while (userGuess != secretNumber) 循环让用户不断输入猜测,直到猜中为止。
  6. 条件判断:根据用户输入与随机数的比较,给出相应的提示信息。
  7. 主函数main() 调用 guessNumberGame() 启动游戏。

这个游戏简单易懂,适合初学者理解 C++ 的基本语法和流程控制。

上一篇:getline在c++中怎么用

下一篇:c++ string类的常用方法

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

c++ weak_ptr

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站