发了
设定一个计数器每次循环加1,就可以了
while循环需要规定作用域,一个if分支也需要规定作用域,{}规定各自的作用域,while(1)是无条件循环,退出条件是你猜对了,如果错误会一直循环下去,continue,break的作用就是在此
程序如下:
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
int number,g_number;
time_t start_time,end_time;
int i=0;
srand(time(NULL));//防止每次程序都产生同样的随机数
number=rand()%100+1;//产生1-100间的随机数
start_time=time(NULL);//记录开始时间
while(1)
{
i++;//记录次数
cout<<"input your number:";
cin>>g_number;
if(g_number<number)
{
cout<<"oh,you number is so little,try again!"<<endl;
continue;
}
else if(g_number>number)
{
cout<<"my lord,you number is so big,try again!"<<endl;
continue;
}
else
{
cout<<"lucky you!you got it!it's "<<number<<endl;
end_time=time(NULL);//记录结束时间
break;
}
}
cout<<"the whole time you use is:"<<end_time-start_time<<"s"<<endl;
cout<<"the times you usded is "<<i<<endl;
return 0;
}
温馨提示:答案为网友推荐,仅供参考