十宗罪3 血凝:用C++编程

来源:百度文库 编辑:高考问答 时间:2024/05/06 18:02:21
在程序中定义一个整形变量,赋以1~100的值,要求用户猜这个数,比较两个数的大小,把结果提示给用户,直到猜对为止。分别使用while,do-while语句实现循环。

#include<iostream>
using namespace std;
void main()
{
int n(36),m;
cout<<"请猜猜这个数是多少:";
while(1)
{
cin>>m;
if(m!=n)
{
if(m<n)
cout<<"你猜的值太小了!"<<endl;
else
cout<<"你猜的值太大了!"<<endl;
cout<<"再猜猜:";
continue;
}
else
break;
}
cout<<"恭喜!猜对了!"<<endl;
}

#include<iostream>
using namespace std;
void main()
{
int n(36),m;
cout<<"请猜猜这个数是多少:";
do{
cin>>m;
if(m<n)
cout<<"你猜的值太小了!再猜猜:";
if(m>n)
cout<<"你猜的值太大了!再猜猜:";
continue;
}while(m!=n);
cout<<"恭喜!你猜对了!"<<endl;
}

可以写一个console程序,用户猜数可以进行输入,比较部分可以写成一个子函数,以上这些都放在while结构体中,循环结束条件为两个数相等,很easy。