7-4 BCD解密 (10分)

基础编程题目集

这题还比较有意思,单单读懂题目就先花了我十几分钟啊。
话不多说,先上题目:
在这里插入图片描述

分析一下,这个题目讲的就是把十进制转换成十六进制,而且最大的就是0x99,所以只用考虑第一位的A-F。
那就先来看看我的一遍过的代码吧:

#include<stdio.h>
void formula(int a);//函数声明

int main()
{
	int a, x, y;
	scanf("%d", &a);//输入BCD数
	if (a > 15)//判断是几位十六进制的数
	{
		x = a / 16;//算算第二位
		y = a - x * 16;//算算第一位
		formula(x);//调用函数
		formula(y);
	}
	else {
		formula(a);
	}
	return 0;
}

void formula(int a)
{
	if (a > 9) printf("%c", a + 'A' - 10);//用了ASCII码输出字符
	else printf("%d", a);//0-9就直接输出数字了
}

写过一些题目,对"\n"的要求非常高,但是这个题目我调用两次这个函数没有用"\n",再完善一点就是在return 0之前输出"\n"。
难就难在怎么输出A-F吧。
附上我同学的代码,另一种方法,也不是不行:

#include <stdio.h>
int main()
{
	int a, b, c; char x;
	scanf("%d",&a);
	b = a % 16;
	c = a / 16;
	if (b == 10) x = '1';
	if (b == 11) x = '2';
	if (b == 12) x = '3';
	if (b == 13) x = '4';
	if (b == 14) x = '5';
	if (b == 15) x = '6';
	if (c == 0)
	{
		if (b >=10)
			switch (x)
			{
			case'1':printf("A"); break;
			case'2':printf("B"); break;
			case'3':printf("C"); break;
			case'4':printf("D"); break;
			case'5':printf("E"); break;
			case'6':printf("F"); break;
			}
		else
			printf("%d", b);
	}
	else
		if (b >= 10)
		{
			switch (x)
			{
			case'1':printf("%dA", c); break;
			case'2':printf("%dB", c); break;
			case'3':printf("%dC", c); break;
			case'4':printf("%dD", c); break;
			case'5':printf("%dE", c); break;
			case'6':printf("%dF", c); break;
			}
			if(b<10)
		 { printf("%d%d", c, b); }
			
		}
	return 0;
}

这是他的原代码,看着好像很多的样子,所以我帮他简化了一下:

#include <stdio.h>
int main()
{
	int a, b, c; char x;
	scanf("%d", &a);
	b = a % 16;
	c = a / 16;
	if (b == 10) x = '1';
	if (b == 11) x = '2';
	if (b == 12) x = '3';
	if (b == 13) x = '4';
	if (b == 14) x = '5';
	if (b == 15) x = '6';
	if (c != 0) printf("%d", c);
	if (b >= 10)
		switch (x)
		{
		case'1':printf("A"); break;
		case'2':printf("B"); break;
		case'3':printf("C"); break;
		case'4':printf("D"); break;
		case'5':printf("E"); break;
		case'6':printf("F"); break;
		}
	else
	{
		printf("%d", b);
	}
	return 0;
}

是不是比他的简洁了很多呢?switch语句也是一种不错的选择。
这般如此,第四题也比较轻轻松松的写完了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值