2-32
在程序中定义一个整型变量﹐赋予1~100 的值。要求用户猜这个数﹐比较两个数的大小,把结果提示给用户,直到猜对为止。分别使用while, do… while语句实现循环。
1 #include<iostream> 2 #include<ctime> 3 using namespace std; 4 5 int main(){ 6 srand(time(0)); 7 int num = rand()%100 + 1; 8 //cout<<num<<endl; 9 int ans; 10 while(1){ 11 cout<<"猜数(0~100)"<<endl; 12 cin>>ans; 13 if(ans > num){ 14 cout<<"大了"<<endl; 15 continue; 16 } 17 else if(ans < num){ 18 cout<<"小了"<<endl; 19 continue; 20 } 21 else{ 22 cout<<"正确"<<endl; 23 break; 24 } 25 } 26 return 0; 27 }

浙公网安备 33010602011771号