C++实现的简单猜数字游戏示例代码

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

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

    const int MAX_NUM = 100;
    int secretNum = rand() % MAX_NUM + 1;
    int guess;
    int attempts = 0;

    cout << "Welcome to the number guessing game!" << endl;
    cout << "I'm thinking of a number between 1 and " << MAX_NUM << ". Can you guess it?" << endl;

    while (true) {
        cout << "Enter your guess: ";
        cin >> guess;
        attempts++;

        if (guess == secretNum) {
            cout << "Congratulations! You guessed the number in " << attempts << " attempts." << endl;
            break;
        } else if (guess < secretNum) {
            cout << "Too low. Try again." << endl;
        } else {
            cout << "Too high. Try again." << endl;
        }
    }

    return 0;
}

在main函数中,我们首先使用srand函数以当前时间作为随机数种子,然后使用rand函数生成一个1到MAX_NUM之间的随机整数作为答案。在while循环中,我们接受用户的输入并与答案进行比较,根据比较结果输出相应的提示信息。如果用户猜对了答案,则输出“Congratulations! You guessed the number in X attempts.”,其中X表示猜测的次数。如果用户猜错了,则输出“Too low. Try again.”或“Too high. Try again.”的提示信息,并在下一轮循环中继续等待用户的输入。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值