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

题目描述

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
#include
#include
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;
}


你可能感兴趣的:(PAT,Advance,level)