当前位置: 代码迷 >> 综合 >> [PAT A1027]Colors in Mars
  详细解决方案

[PAT A1027]Colors in Mars

热度:62   发布时间:2023-12-15 06:25:04.0

[PAT A1027]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.

输入格式

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

输出格式

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.

输入样例

15 43 71

输出样例

#123456

解析

  1. 题目大意:就是说火星人通常使用RGB三色表示他们的颜色,共有六位,高两位是表示Red,中间两位表示Green,最低两位表示Blue,但是他们的进制是13进制,所以我们需要换算成13进制对他们表示的颜色输出(6位),如果不够2位,前面用0来补
  2. 我的思路就是写一个转换函数,对每个颜色转换一下,一起输出就行
#include<iostream>
#include<string>
using namespace std;
string trans(int num)
{
    int high, low;     //一个存放高位,一个存放低位string dest = "";low = num % 13;high = num / 13;if (high >= 10) dest += (char)(high - 10 + 'A');else dest += (char)(high + '0');if (low >= 10) dest += (char)(low - 10 + 'A');else dest += (char)(low + '0');return dest;
}
int main()
{
    int red, green, blue;cin >> red >> green >> blue;cout << "#" << trans(red) << trans(green) << trans(blue);return 0;
}
  1. 而柳神的代码是值得我们学习的,她使用了一个数组,存储了{0123456789ABC},这样就可以把某一位与数组的下标构成对应关系,这种手法经常使用,而且能够大大简化代码量,是我必须要改进的地方。(贴柳神的代码,谨供学习,侵删)
#include <cstdio>
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;
}

水平有限,如果代码有任何问题或者有不明白的地方,欢迎在留言区评论;也欢迎各位提出宝贵的意见!