思路:
使用字符串存儲輸入的待轉換數及轉換後的結果,先轉換爲十進制,再從十進制轉換到目標進制。
解答:
#include <cstdio>
#include <cstring>
using namespace std;
int char_to_oct(int a, char input[]) {//按進制a將input字符串轉換爲10進制數
int sum = 0, product = 1;
for (int i = strlen(input) - 1; i >= 0; i--){
if (input[i] <= '9')
sum += (input[i] - '0') * product;
else if (input[i] <= 'F')
sum += (input[i] - 'A' + 10) * product;
else if (input[i] <= 'f')
sum += (input[i] - 'a' + 10) * product;
product *= a;
}
return sum;
}
void oct_to_char(int temp, int b, char output[]) { //將10進制數temp轉換成字符表示的b進制數,存儲在字符串output中
int i = 0;
do {
int k = temp % b;
if (k <= 9)
output[i++] = '0' + k; // int轉char的方法
else
output[i++] = 'A' + (k - 10);
temp /= b;
} while (temp != 0);
output[i] = '\0'; // 必須添加結束符, 不然strlen無法正確判別長度
}
int main() {
int a, b; // 原進制,新進制
char input[100]; //待轉換的數
while (scanf("%d %s %d", &a, input, &b) != EOF) {
int temp = char_to_oct(a, input); // temp是待轉換數的十進制表示
if (b == 10) { // 如果新進制是十進制,則只需進行第一個轉換
printf("%d\n", temp);
continue; // 跳出本次本組輸入的循環,接收下一組輸入
}
char output[100]; // 存放結果的字符數組
oct_to_char(temp, b, output); // 十進制轉換爲目標進制b
for(int j = strlen(output) - 1; j >= 0; j--)
printf("%c", output[j]);
printf("\n");
}
return 0;
}
筆記:
- 靈活使用加減運算實現int和char之間的轉換
坑:
- 輸入可能包括A~F的字符,不一定全是數字
- 最後的結果不能使用printf("%s\n", r)輸出,因爲十進制向目標進制的轉換是從後向前地得到每位結果,需要逆序打印。
參考:
https://blog.csdn.net/myRealization/article/details/80154726