You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <stdio.h>
#include <string.h>
#include <math.h>
// 函数:将单个字符转换为对应的数值
int charToVal(char c) {
if (c >= '0' && c <= '9') return c - '0';
else if (c >= 'A' && c <= 'F') return c - 'A' + 10;
else if (c >= 'a' && c <= 'f') return c - 'a' + 10;
else return -1; // 非法字符
}
// 函数:将数值转换为对应的字符
char valToChar(int val) {
if (val >= 0 && val <= 9) return '0' + val;
else return 'A' + val - 10;
}
// 函数将字符串形式的数从fromBase进制转换为十进制
int convertToDecimal(char *num, int fromBase) {
int len = strlen(num);
int power = 1; // 表示当前位的权重
int numDecimal = 0; // 存放结果的十进制数
for (int i = len - 1; i >= 0; i--) {
int val = charToVal(num[i]);
if (val < 0 || val >= fromBase) {
printf("输入错误: 你所输入的数 %c 不是 %d进制\n", num[i], fromBase);
return -1; // 如果有非法字符,则返回 -1
}
numDecimal += val * power;
power *= fromBase; // 计算权重
}
return numDecimal;
}
// 函数将十进制数转换为toBase进制的字符串形式
void convertFromDecimal(int numDecimal, int toBase, char *result) {
int index = 0; // 指示result数组中的当前位置
if (numDecimal == 0) {
result[index++] = '0'; // 特例处理零
}
while (numDecimal > 0) {
int remainder = numDecimal % toBase;
result[index++] = valToChar(remainder);
numDecimal /= toBase;
}
result[index] = '\0'; // 添加字符串结束符
// 反转字符串
for (int i = 0; i < index / 2; i++) {
char temp = result[i];
result[i] = result[index - i - 1];
result[index - i - 1] = temp;
}
}
int main() {
char num[20];
int fromBase, toBase;
char result[20];
printf("请输入数字: ");
scanf("%s", num);
printf("请输入当前数字的进制(2 to 16): ");
scanf("%d", &fromBase);
printf("请输入您预期得到数字的进制(2 to 16): ");
scanf("%d", &toBase);
// 转换为十进制
int numDecimal = convertToDecimal(num, fromBase);
if (numDecimal < 0) {
return 1; // 如果转换出错则直接返回
}
// 转换为目标进制
convertFromDecimal(numDecimal, toBase, result);
printf("转化后的数字: %s\n", result);
return 0;
}