PAT甲级A1027答案(使用C语言)

本文介绍了一种将地球上的十进制颜色值转换为火星计算机使用的十三进制RGB值的方法。通过实例讲解了如何将三个十进制颜色值(红、绿、蓝)转换为一个六位的十三进制数,详细解释了转换过程中的注意事项,如单个颜色值小于13时的零填充规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

People in Mars represent the colors in their computers in a similar way as the Earth people. That is, a color is represented by a 6-digit number, where the first 2 digits are for Red, the middle 2 digits for Green, and the last 2 digits for Blue. The only difference is that they use radix 13 (0-9 and A-C) instead of 16. Now given a color in three decimal numbers (each between 0 and 168), you are supposed to output their Mars RGB values.

Input Specification:

Each input file contains one test case which occupies a line containing the three decimal color values.

Output Specification:

For each test case you should output the Mars RGB value in the following format: first output #, then followed by a 6-digit number where all the English characters must be upper-cased. If a single color is only 1-digit long, you must print a 0 to its left.

Sample Input:

15 43 71

Sample Output:

#123456

题目要求总结

让你输入三个十进制数,然后转换为一个#+六位数输出,而这个六位数是由三个由十进制数转化而来的十三进制数。另外,十三进制数的表示方法为1-13对应到(0-9,A-C),如果转换为十三进制时只有一位数,那要在这一位数的左边补零

思路

1.由于进制转换的方法通常是算出余数作为对应进制的数,所以我们在最开始设置一个字符类型的数组,然余数的值与数组的索引相对应进而转换为十三进制数

char radix[13] = {'0','1','2','3','4','5','6',
				'7', '8', '9', 'A', 'B', 'C'};

2.设置一个3*2的二维数组来存放最终转换成功的十三进制数,因为一个十进制数对应两个两位的十三进制数;
3.开始转换时,要先判断这个数是否为小于13的数,因为如果这个数小于十三的话,转换出来的时候会只有一位数,这种情况是需要单独补0的,所以要单独拿出来判断

if(color_num[j] < 13) {
			result[j][0] = '0';  //j代表当前在进行第j+1个十进制数的转换,而转换为十三进制时第一位要补充为0
			result[j][1] = radix[color_num[j] % 13];//第二位才为十三进制数
		}

4.如果需要转换的十进制数大于13的话,则算出余数然后倒叙放入result[j]数组中

while(color_num[j] != 0){
			 
				result[j][k] = radix[color_num[j] % 13];
				color_num[j] /= 13;
				k--;
			}

5.转换完成后,输出“#”后,按顺序输出所有字母

	printf("#");
	for(int m=0; m < 3; m++){
		for(int n=0; n < 2; n++){
			printf("%c", result[m][n]);
		}
	}
	printf("\n");
	return 0;

完整代码

#include<stdio.h>
#include<algorithm>
#include<string>
using namespace std;

int color_num[3], mars_color[6];
char radix[13] = {'0','1','2','3','4','5','6',
				'7', '8', '9', 'A', 'B', 'C'};

int main(){
	for(int i = 0; i < 3; i++){
		scanf("%d", &color_num[i]);
		}		
	int j = 0;
	char result[3][2];
	for(j ; j < 3; j++){
		int  k = 1;
		if(color_num[j] < 13) {
			result[j][0] = '0';  //j代表当前在进行第j+1个十进制数的转换,而转换为十三进制时第一位要补充为0
			result[j][1] = radix[color_num[j] % 13];//第二位才为十三进制数
		}
		else{
			while(color_num[j] != 0){
			 
				result[j][k] = radix[color_num[j] % 13];
				color_num[j] /= 13;
				k--;
			}
		}
	}
	printf("#");
	for(int m=0; m < 3; m++){
		for(int n=0; n < 2; n++){
			printf("%c", result[m][n]);
		}
	}
	printf("\n");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值