猜数字游戏的实现

hello,大家好,我是一代。今天我们来讲猜数字游戏的实现。

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<windows.h>
#include<string.h>
#define Count 5
void menu()
{
	printf("**************************\n");
	printf("***   1.play   0.exit  ***\n");
	printf("**************************\n");
}
void game2()
{
	char input[20] = { 0 };
	while (1)
	{
		printf("请注意,您的将在一分中内关机,如果输入:我是猪,就取消关机\n请输入>:");
		system("shutdown -s -t 60");
		scanf_s("%s", input, 20);
		if (strcmp(input, "我是猪") == 0)
		{
			printf("已取消关机\n");
			system("shutdown -a");
			break;
		}
	}
}
void game1()
{
	int count = 0;
	int ret = 1 + rand() % 100;
	while (1)
	{
		printf("请输入数字:>");
		int i = 0;
		scanf_s("%d", &i);
		if (i > ret)
		{
			printf("猜大了\n");
			count++;
		}
		else if (i < ret)
		{
			printf("猜小了\n");
			count++;
		}
		else
		{
			printf("恭喜你,猜对了\n");
			break;
		}
		if (count == Count)
		{
			game2();
			break;
		}
	}
}
int main()
{
	srand((unsigned int)time(NULL));
	int n = 0;
	do
	{
		menu();
		printf("请选择:>");
		scanf_s("%d", &n);
		switch (n)
		{
		case 1:
			game1();
			n = 0;
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("输入错误,请重新输入\n");
			break;
		}
	} while (n);
}

其中用到了strcmp函数,其需要的头文件为#include<string.h>,函数原型为extern int strcmp(const char *s1,const char * s2);功能是比较两个字符串的大小。一般形式:strcmp(字符串1,字符串2)
说明:
当s1<s2时,返回为负数
当s1=s2时,返回值= 0
当s1>s2时,返回正数

比较时两个字符串自左向右逐个字符比较,比较的是ASCII值,直到出现不同的字符或遇到'\0'为止,如"C"<"D" "a">"A" "compliment">"complement".

这里宏定义的Count是猜数字的次数,如果猜了Count次还没有猜对,就会进入game2,也就是上一篇讲扫雷时的博客,game2中system("shutdown -s -t 60")的意思是60秒后关机,当输入我是猪时就会执行system("shutdown -a")取消关机,当然你也可以自己把代码改一下,改成我是帅哥或者把关机时间改一下也可以等等都可以。开头switch中n=0是为了让游戏进行一次结束。

谢谢大家的阅读,我是一代,我们下篇博客见。

  • 26
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值