以下是将一个十进制数转换为任意进制的C语言实现。其中,输入的十进制数为decimal,目标进制为base,输出结果存储在字符数组result中。
void decimalToBase(int decimal, int base, char* result) { const char digit[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int quotient = decimal; int remainder; int i = 0; if (decimal == 0) { result[0] = '0'; result[1] = '\0'; return; } while (quotient != 0) { remainder = quotient % base; result[i++] = digit[remainder]; quotient /= base; } result[i] = '\0'; // Reverse the result for (int j = 0; j < i / 2; j++) { char temp = result[j]; result[j] = result[i - j - 1]; result[i - j - 1] = temp; } }
调用该函数的示例代码:
#include <stdio.h> #include <string.h> int main() { int decimal = 12345; int base = 16; char result[100]; decimalToBase(decimal, base, result); printf("%d in base %d is %s\n", decimal, base, result); return 0; }
以上代码的输出结果是:
12345 in base 16 is 3039
评论