【C语言】C基本练习4 (猜数字游戏、模拟密码登陆、大小写字符转换)

(一)猜数字游戏

  • 游戏实现部分: 由主函数、菜单子函数、游戏子函数构成
  • 游戏子函数中涉及到随机数的产生rand函数的认识和应用,通过所输入的数字与随机数相比;产生三种情况:(1)输入的数字比随机数大;(2)输入的数字比随机数小;(3)一样大;
    利用死循环进行下去。
    代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
void menu()
{
	printf("************************************\n");
	printf("*********** 1.play *****************\n");
	printf("************0.exit *****************\n");
	printf("************************************\n");
}
void game()
{
	int random_num = rand() % 1000 + 1;

	int grass = 0;
	while (1)
	{
		printf("请输入猜的数字>:");
		scanf("%d", &grass);
		if (grass > random_num)
		{
			printf("猜大了\n");
		}
		else if (grass < random_num)
		{
			printf("猜小了\n");
		}
		else
		{
			printf("恭喜你,猜对了\n");
			break;
		}
	}
}
int main()
{
	int input = 0;
	srand((unsigned)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;
	system("pause");
}

(二)模拟密码登陆

//模拟用户登陆情景,并且只能登陆三次。(只允许输入三次密码,如果密码正确则提示登陆成功,如果三次密码均输入错误,则退出程序)

  • 程序中涉及到strcmp函数,功能:比较字符串s1和s2;
  • 一般形式:strcmp(字符串1,字符串2);
  • 说明:当s1 > s2时 ,返回值大于0;当s1 < s2时,返回值大于0;当s1 = s2时,返回值=0;
  • 用strcmp函数与密码相比看是否等于0,是输出登陆成功,break跳出循环;
    代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
	int i = 0;
	char password[20] = { 0 };
	for (i = 0; i < 3; i++)
	{
		printf("请输入密码:\n");
		scanf("%s", password);
		if (strcmp(password, "123456") == 0)
		{
			printf("登陆成功\n");
			break;
		}
		else
			printf("错误,请重新输入:\n");
	}
	if (i == 3)
	{
		printf("三次密码均输入错误\n");
	}
	system("pause");
	return 0;
}

(三)大小写字符转换

//编写程序,键盘接收字符,小写字符输出相应的大写字符,大写字符输出相应的小写 字符,数 字 不输出

  • 键盘只接收字符涉及到EOF 文本结束标志,getchar,putchar等应用
  • 大小写转换:小写转换大写(ch-32);大写转换小写(ch+32);
    代码如下:
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
int main()
{
	int ch = 0;
	while ((ch=getchar())!= EOF)
	{
		if (ch >= 'a'&& ch <= 'z')
		{
			putchar(ch - 32);
		}
		else  
		if (ch >= 'A'&&ch <= 'Z')
		{
			putchar(ch + 32);
		}
		printf("\n");
	}
	system("pause");
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值