因此,我在创建递归函数以将以 2-10 为基数的数字转换为以 2-16 为基数的数字时遇到了麻烦。我需要它返回一个字符串(显然,由于基数大于 10)。
这是我的功能:
main 会这样调用它:
answer = baseConversion(101, 10, 2);
我将十六进制作为常量字符:
const char Hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char * baseConverter(int number,int currbase, int base){
if(currbase != 10){
number = base10Converter(number, currbase); //converts the number to base of 10
currbase = 10;
}
if(number == 0 || base==10){
return number;
}
int r = number%base;
printf("%c", Hex[r]);
//return (number % base) + 10*baseConverter(number /base, currbase, base); // this gives the answer as an integer.
return Hex[r]+ && baseConverter(number /base, currbase, base) // I dont know what to add here to add the characters together
}
我在返回语句和递归调用方面需要帮助。 我是否需要在函数中声明一个 char 数组,然后将我从 hex[r] 获得的字符附加到它?如果是这样,我该怎么做,因为我无法更改参数
最佳答案
int
没有基础,它们只有值。你如何显示,或用字符串表示,有基础。因此,currBase
没有意义,除非您从要转换的值的字符串表示开始。baseConverter
,被定义为返回一个字符串;由于没有为该字符串传递空间,因此必须为其分配空间。- 因此,对于递归情况,您将调用
baseConverter
为您提供一个字符串作为数字的其余部分,并使用它来制作一个新字符串(您需要分配的),确保在完成后释放从递归调用中获得的字符串。
关于使用递归将一个基数转换为另一个基数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26445488/