甲级PAT 1027 Colors in Mars(十进制转十三进制)

1027 Colors in Mars (20 分)

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

题目要求: 

给出三个十进制数,把他们转化为十三进制,开头加#,英文字符大写

解题思路:

因为0-168正好是两位十三进制数,所以将十进制数除以13,商高位,余数低位。

完整代码:

#include
using namespace std;

char trav(int x){
	if(x<=9) return x+'0';
	else if(x==10) return 'A';
	else if(x==11) return 'B';
	else if(x==12) return 'C';
}
int main(){
	int a[3],i;
	for(i=0;i<3;i++){
		cin>>a[i];
		if(i==0) cout<<"#";
		cout<

上述代码还可以进行优化。用一个字符数组存储0-C,对应下标代表对应字符,就不需要写个函数进行转化

#include 
using namespace std;
int main() {
    char c[14] = {"0123456789ABC"};
    printf("#");
    for(int i = 0; i < 3; i++) {
        int num;
        scanf("%d", &num);
        printf("%c%c", c[num/13], c[num%13]);
    }
    return 0;
}

 

你可能感兴趣的:(PAT甲级)