前面我也发布过纯C的猜数字游戏
有兴趣的小伙伴也可以看一下
最简单的猜数字游戏(纯C)_Koi279的博客-CSDN博客
如果大家对违法输入(比如输入特殊字符和字母)不明白的,我也有相关文章讲解
有关c\c++违规输入相关问题_Koi279的博客-CSDN博客
先看一下效果
这里我设置了四个难度
分别为
1~100
1~1000
1~10000
1~100000
的随机数。
vs下可执行代码如下
#include<iostream>
using namespace std;
void meau1()
{
cout << "\t\t******************" << endl;
cout << "\t\t**1.play 0.exit**" << endl;
cout << "\t\t******************" << endl;
}
void meau2()
{
cout << "\t 1.简单";
cout << "\t 2.一般";
cout << "\t 3.困难";
cout << "\t 4.地狱" << endl;
}
void game(int a)
{
cout << "\t\t请输入一个1~" << a << "的数字" << endl;
srand((unsigned)time(NULL));
int ret = rand() % a + 1;
int n; while (1)
{
cin >> n;
if (n > ret)
cout << "\t猜大了!" << endl;
else if (n < ret)
cout << "\t猜小了!" << endl;
else
{
cout << "\t恭喜你,猜对了!" << endl; break;
}
}
}
int main()
{
cout << "\t\t 猜数字游戏" << endl;
meau1(); int c1, c2;
do
{
cout << "\n\t\t请选择:";
back1:
cin >> c1;
if ((int)c1 != 1 && (int)c1 != 0)
{
cout << "选择错误,请按指示选择!" << endl;
goto back1;
}
switch (c1)
{
case 1:
cout << "\t\t请选择游戏难度:\n" << endl;
meau2();
back2:
cin >> c2;
switch (c2)
{
case 1: game(100); break;
case 2: game(1000); break;
case 3: game(10000); break;
case 4: game(100000); break;
default:cout << "\t\t选择错误,请按指示选择!" << endl; goto back2;
}
break;
case 0:
cout << "退出游戏" << endl; break;
}
} while (c1);
return 0;
}
DEV-C++下 可执行代码如下:
#include<iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
void meau1()
{
cout << "\t\t******************" << endl;
cout << "\t\t**1.play 0.exit**" << endl;
cout << "\t\t******************" << endl;
}
void meau2()
{
cout << "\t 1.简单";
cout << "\t 2.一般";
cout << "\t 3.困难";
cout << "\t 4.地狱" << endl;
}
void game(int a)
{
cout << "\t\t请输入一个1~" << a << "的数字" << endl;
srand((unsigned)time(NULL));
int ret = rand() % a + 1;
int n; while (1)
{
cin >> n;
if (n > ret)
cout << "\t猜大了!" << endl;
else if (n < ret)
cout << "\t猜小了!" << endl;
else
{
cout << "\t恭喜你,猜对了!" << endl; break;
}
}
}
int main()
{
cout << "\t\t 猜数字游戏" << endl;
meau1(); int c1, c2;
do
{
cout << "\n\t\t请选择:";
back1:
cin >> c1;
if ((int)c1 != 1 && (int)c1 != 0)
{
cout << "选择错误,请按指示选择!" << endl;
goto back1;
}
switch (c1)
{
case 1:
cout << "\t\t请选择游戏难度:\n" << endl;
meau2();
back2:
cin >> c2;
switch (c2)
{
case 1: game(100); break;
case 2: game(1000); break;
case 3: game(10000); break;
case 4: game(100000); break;
default:cout << "\t\t选择错误,请按指示选择!" << endl; goto back2;
}
break;
case 0:
cout << "退出游戏" << endl; break;
}
} while (c1);
return 0;
}