猜数游戏。程序预制一个常数(称为幻数),让用户猜,猜对时给出正确信息,否则会给出是大了还是小了的提示。
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void guess(int num);
int main()
{
int num;
srand(time(0));
num = rand() % 1000;//生成随机数
guess(num);
return 0;
}
void guess(int num)
{
int n, count=1;
do
{
cout << "在一千以内猜一个数" << endl;
cin >> n;
if(n==num)
{
cout << "你猜对了!" << endl;
break;
}
else if (n < num)
{
cout << "猜小啦" << endl;
}
else
{
cout << "猜大啦" << endl;
}
count++;
} while (n != num);
cout << "经过" << count << "次,你猜对了" << endl;
}