正常的猜数字游戏代码与注释:
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<time.h>
#include<stdio.h>
void menu()
{
printf("******************\n");
printf("*** 1.play *****\n");
printf("*** 0.exit *****\n");
printf("******************\n");
}
void game()
{
//1.生成随机数(1-100)
int ret = rand() % 100 + 1;//1-100,n%100余数的范围0-99
//2.猜数字
int guess = 0;
int count = 8;//猜8次
while (count)
{
printf("请猜数字:>");
scanf("%d", &guess);//猜值
if (guess < ret)
{
printf("猜小了\n");
}
else if (guess > ret)
{
printf("猜大了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
count--;
}
if (count == 0)
{
printf("猜失败了,正确的数字是:%d\n", ret);
}
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("请选择:>");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("输入错误\n");
break;
}
} while (input);
return 0;
}
正常的效果呈现:
![](https://i-blog.csdnimg.cn/blog_migrate/9fbc601c78411c956aa7bff0839b7495.png)
关机程序的代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<windows.h>
using namespace std;
int main()
{
system("shutdown -s -t 60");
return 0;
}
将猜对设置成关机
带关机的猜字游戏:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<windows.h>
#include<stdlib.h>
#include<time.h>
#include<stdio.h>
using namespace std;
void menu()
{
printf("******************\n");
printf("*** 1.play *****\n");
printf("*** 0.exit *****\n");
printf("******************\n");
}
void game()
{
int ret = rand() % 100 + 1;
int guess = 0;
int count = 10;
while (count)
{
printf("请猜数字:>");
scanf("%d", &guess);
if (guess < ret)
{
printf("猜小了\n");
}
else if (guess > ret)
{
printf("猜大了\n");
}
else
{
printf("恭喜你,猜对了,奖励关机\n");
system("shutdown -s -t 10");
break;
}
count--;
}
if (count == 0)
{
printf("猜失败了,正确的数字是:%d\n", ret);
}
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("请选择:>");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("输入错误\n");
break;
}
} while (input);
return 0;
}
效果展示:
![](https://i-blog.csdnimg.cn/blog_migrate/95525787998c53edcac2cbb7e88fc2e8.png)
![](https://i-blog.csdnimg.cn/blog_migrate/f3fb314827fd2726d325ea75b4bee223.png)
防止关机方法和代码详细解析明天发布,需要的小伙伴记得关注我,创作不易,欢迎点赞。