#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[20]; // 存储原始数字
char hex[20]; // 存储十六进制数
long int num; // 原始数字
int base1, base2; // 原始数字的基数和目标基数
printf("Enter the number: ");
fgets(str, sizeof(str), stdin);
printf("Enter the base of the number: ");
scanf("%d", &base1);
printf("Enter the base to convert to: ");
scanf("%d", &base2);
// 将 str 转换为10进制数字
num = strtol(str, NULL, base1);
// 将 10进制数 转换为 对应为 base2 的数字
sprintf(hex, "%lx", num);
// 输出结果
printf("%s in base %d = %s in base %d\n", str, base1, hex, base2);
return 0;
}
这个程序需要输入要转换的数字、它的起始基数和目标基数。在主函数中我们首先使用 fgets
读取用户输入的字符串并将其存储在 str
变量中,然后使用 strtol
函数将这个字符串转换为10进制数。最后,使用 sprintf
函数将10进制数转换为目标基数的数字,并将其存储在 hex
变量中。最后,打印输出结果。就完成了。