首页 > 试题广场 >

在程序中定义一个整型变量,赋以 1~100 的值,要求用户猜

[问答题]

在程序中定义一个整型变量,赋以 1~100 的值,要求用户猜这个数,比较两个数的大 小,把结果提示给用户,直到猜对为止。分别使用 whiledo…while 语句实现循环。

推荐

解:

//使用 while 语句
#include <iostream.h>
 
void main() {
int n = 18;
int m = 0;
while(m != n)
{
cout << "请猜这个数的值为多少?(0~~100):"; 
cin >> m;
if (n > m)
cout << "你猜的值太小了!" << endl; 
else if (n < m)
cout << "你猜的值太大了!" << endl; 
else
cout << "你猜对了!"
<< endl;
}
}
//使用 do…while 语句
#include <iostream.h>
 
void main() { 
int n = 18; 
int m = 0; 
do{
cout << "请猜这个数的值为多少?(0~~100):"; 
cin >> m;
if (n > m)
cout << "你猜的值太小了!" << endl; 
else if (n < m)
cout << "你猜的值太大了!" << endl; 
else
cout << "你猜对了!" << endl; 
}while(n != m);
}
 



















程序运行输出:

请猜这个数的值为多少?(0~~100):50

你猜的值太大了!

请猜这个数的值为多少?(0~~100):25

你猜的值太大了!

请猜这个数的值为多少?(0~~100):10

你猜的值太小了!

请猜这个数的值为多少?(0~~100):15

你猜的值太小了!

请猜这个数的值为多少?(0~~100):18

你猜对了!

发表于 2018-04-18 20:58:02 回复(0)
#include<iostream> using namespace std; int main(){ int n=1+rand()%100,x; cout<<“请输入一个整数(0~100):”; cin>>x; while(x!=n){ if(x</iostream>
发表于 2020-01-02 19:54:52 回复(0)