猜数字游戏

最近在看《c++ programming for the absolute beginner》,一方面是为了提高自己读英文技术书籍的能力,另一方面也是想对c++编程基础查漏补缺。看到书上有一个猜数字的小游戏代码。于是我自己也编了一个,处理了一些用户输入不符合规定的情况。此小游戏就是猜1-100之间的数。猜对了游戏成功,可选择退出,或者再来一次。代码在vs2008中运行成功。代码如下:



#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{	
	while(true)
	{
		int InputNum,CurrentMax=100,CurrentMin=1,Count=1;
		bool Indicator=true;
		char InputWord;
		srand(GetTickCount());                              //生成随机数,得到自开机以来的系统时间
		int RightNum=rand()%100+1;                          //保证生成的随机数在1-100之间。如果要保证随机数在min-max之间,则写成rand()%(max-min+1)+min
		cout<<"Let's start the Number Guessing Game!"<<endl;
		cout<<"Please type in a number between 0 to 100(including 0 and 100)"<<endl;
		while(Indicator)
		{	
			cin>>InputNum;
			if(InputNum>=1&&InputNum<=100)                    //输入数字,如果输入的数字不是1-100间的数字,则要求重新输入。此程序未考虑用户输入不是数字的情况
			{
			if(InputNum<RightNum)                             //如果输入数字小于答案,则将下限设为此输入值,并提示用户缩小后的输入范围
			{
				cout<<InputNum<<" is too small. And you've already tried "<<Count<<" times."<<endl;
				CurrentMin=InputNum;
				cout<<"################################################"<<endl;
				cout<<"Please input a number between "<<CurrentMin<<" and "<<CurrentMax<<endl;		
				Count++;                                      //用户输入次数计数加1
			}
			else if(InputNum>RightNum)                       //如果输入数字大于答案,则将上限设为此输入值,并提示用户缩小后的输入范围
			{
				cout<<InputNum<<" is too big. And you've already tried "<<Count<<" times."<<endl;
				CurrentMax=InputNum;
				cout<<"################################################"<<endl;
				cout<<"Please input a number between "<<CurrentMin<<" and "<<CurrentMax<<endl;
				Count++;
			}
			else if(InputNum==RightNum)                     //用户输入等于答案,则提示用户游戏成功,并询问用户是要再来一次还是退出
			{
				cout<<"^-^Congratulations! "<<InputNum<<" is the right number. You've tried "<<Count<<" times to win the game"<<endl;
				cout<<"################################################"<<endl;
				cout<<"If you want to try again, please input y."<<endl;
				cout<<"If you want to quit, please input n."<<endl;
				bool Indicator2=true;
				while(Indicator2)                             
				{
					cin>>InputWord;
					if(InputWord=='y')                    //如果用户输入‘y’,则再来一次
					{
						Indicator2=false;
						Indicator=false;
					}
					else if(InputWord=='n')               //如果用户输入‘n’,则退出游戏
					{
						return 0;
					}
					else                                  //如果输入为既不是‘y’,也不是‘n’的字母,则提示用户必须输入‘y’或者‘n’。此处不考虑用户输入不是字母的情况。
					{
						cout<<"Please input \"y\" or \"n\"."<<endl;
					}
				}
			}
			}
			else
			{
				Indicator=false;
			}
		}
	}
}


某次代码运行的结果截图如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值