思路:
第一关:利用srand和rand生成0-9的随机数,再判断输入数与生成数的大小关系即可。
第二关:利用srand和rand生成100-999的三位随机数,对输入数与生成数进行数位拆分,再从高到低逐位比较即可。
C++代码:
#include <bits/stdc++.h>
using namespace std;
void g1(){
int n, num, cnt = 1, flag = 0;
srand(time(0));
num = rand() % 10;
do{
cin >> n;
if (n == num){
cout << "Congratulations!";
flag = 1;
break;
}
else if (n > num) cout << "Bigger than the answer" << endl;
else cout << "Smaller than the answer" << endl;
}while (cnt < 5);
if (flag == 0) cout << "Mission Fail";
}
void g2(){
int n, num, cnt = 1, flag = 0;
srand(time(0));
num = (rand() % 999 - 100 + 1) + 100;
do{
cin >> n;
if (n == num){
cout << "Mission Complete!";
flag = 1;
break;
}
else{
if (n / 100 == num / 100) cout << "True ";
else cout << "False ";
if (n % 100 / 10 == num % 100 / 10) cout << "True ";
else cout << "False ";
if (n % 10 == num % 10) cout << "True";
else cout << "False";
}
cnt++;
}while (cnt < 4);
if (flag == 0) cout << "Mission Fail";
}
int main(){
g1();
g2();
return 0;
}
望采纳。
简单
可以根据这个实例进行完善【C语言猜数字游戏(详解)】,链接:https://blog.csdn.net/weixin_67913271/article/details/126427676
直接从前面那个老哥的代码里改的,加了一个生成一个1.txt并打印输出的功能,另外提一句,这玩意只能在windows平台使用(因为用的dos指令),所以如果是作业而且电脑判题就一般不行,第二关打印有点bug,就看你能不能接受咯,可以接受的话结题也给前面那位老哥吧,我懒癌发作懒得写文件操作了
#include <bits/stdc++.h>
using namespace std;
void g1()
{
int n, num, cnt = 1, flag = 0;
srand(time(0));
num = rand() % 10;
do
{
cin >> n;
if (n == num)
{
cout << "Congratulations!";
system("echo Congratulations! >> 1.txt");
flag = 1;
break;
}
else if (n > num)
{
cout << "Bigger than the answer" << endl;
system("echo Bigger than the answer >> 1.txt");
}
else
{
cout << "Smaller than the answer" << endl;
system("echo Smaller than the answer >> 1.txt");
}
} while (cnt < 5);
if (flag == 0)
{
cout << "Mission Fail" << endl;
system("echo Smaller than the answer >> 1.txt");
}
}
void g2()
{
int n, num, cnt = 1, flag = 0;
srand(time(0));
num = (rand() % 999 - 100 + 1) + 100;
do
{
cin >> n;
if (n == num)
{
cout << "Mission Complete!";
system("echo Mission Complete! >> 1.txt");
flag = 1;
break;
}
else
{
if (n / 100 == num / 100)
{
cout << "True ";
system("echo True >> 1.txt");
}
else
{
cout << "False ";
system("echo True >> 1.txt");
}
if (n % 100 / 10 == num % 100 / 10)
{
cout << "True ";
system("echo True >> 1.txt");
}
else
{
cout << "False ";
system("echo False >> 1.txt");
}
if (n % 10 == num % 10)
{
cout << "True";
system("echo True >> 1.txt");
}
else
{
cout << "False";
system("echo True >> 1.txt");
}
}
cnt++;
} while (cnt < 4);
if (flag == 0)
{
cout << "Mission Fail";
system("echo Mission Fail >> 1.txt");
}
}
int main()
{
g1();
g2();
return 0;
}