C++猜数字小游戏

一、随机数

本文采用time(0)作为srand()函数的种子生成随机数,time(0)为1970年1月1日0时0分0秒到此时的秒数。本文随机数范围控制在0~100,可根据自己需求进行更改。

二、次数

本文代码中times代表次数,可根据自己需求进行更改。

三、胜负条件

数字猜对即为胜利,次数耗尽前仍未猜中即为失败,结束后继续游玩请输入1,退出游戏输入其他任意字符。(本文设置游戏在输入正确范围的数字后才会开始,输入错误范围的数字仍会减少次数)

四、代码

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{

   int num1 = 0;
   int num2 = 0;
   int num3 = 1;
   int times = 7;
    while (num3 == 1)
   {
        times = 7;
       srand((unsigned int)time(NULL));
       num1 = rand() % 100;
       cout << "游戏开始,请输入你的猜测结果,共"<<times<<"次机会,数字范围为0~100:" << endl;
       cin >> num2;

       while (num2 > 100 || num2 < 0)
       {
           cout << "输入错误,请重新输入0~100的数字:" << endl;
           cin >> num2;
       }
       times -= 1;
       cout << "游戏正式开始"<< endl;
       while (1)
       {
           if (times == 0)
           {
               cout << "次数用尽,游戏失败" << endl;
               break;
           }
           if (num2 > num1)
           {
               cout << "你猜测的数字过大,剩余次数:"<<times<<",请重新输入:" << endl;
               cin >> num2;
               times -= 1;
           }
           if (num2 < num1)
           {
               cout << "你猜测的数字过小,剩余次数:" << times << ",请重新输入:" << endl;
               cin >> num2;
               times -= 1;
           }
           if (num2 == num1)
           {
               cout << "猜对了,数字为" << num1 << endl;
               break;
           }
           if (num2 > 100 || num2 < 0)
           {
               cout << "请输入正确范围的数字,剩余次数:" << times << ",请重新输入:" << endl;
               cin >> num2;
               times -= 1;
           }
       }
       
      
       cout << "继续游玩请输入1,退出游戏输入其他任意字符" << endl;
       cin >> num3;
   }

    system("pause");
    return  0;

}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇

)">
下一篇>>