小白初学C++ 猜数游戏
C++ while语句的猜数游戏
话不多说这里直接上代码
#include <iostream>
#include <ctime>
using namespace std;
int main(){
srand((unsigned int)time(NULL));
int sum=rand()%100+1;
int i;
cout<<"请输入您要猜的数字:"<<endl;
while(1){
cin>>i;
if(i>sum){
cout<<"您猜的数字偏大,请再猜一次:"<<endl;
}else if(i<sum){
cout<<"您猜的数字偏小,请在猜一次:"<<endl;
}else{
cout<<"恭喜您,猜对了。"<<endl;
break;
}
}
system("pause");
ruturn 0;
}
注释:
#include <ctime> //这是time系统时间头文件
srand((unsigned int)time(NULL))
//这是添加随机数种子,作用是利用当前系统时间生成随机数,防止每次随机数一样。
int sum=rand()%100+1;
//定义产生的随机数在0~99之间,同时因为第一次产生的随机数是固定的,所以+1.
while(1){}//1是为了除了当产生的随机数等于你猜的数时才退出循环。
if(i>sum){
cout<<"您猜的数字偏大,请再猜一次:"<<endl;//猜数大时。
}else if(i<sum){
cout<<"您猜的数字偏小,请在猜一次:"<<endl;//猜数小时。
}else{
cout<<"恭喜您,猜对了。"<<endl;
break;//退出循环。
}
system("psaue")//暂停
return 0;//一定不能缺少这行代码。