因此,我很难创建一个递归函数,将一个数字从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数组,然后将从十六进制获得的字符追加到函数中?如果是这样的话,我该如何做呢?因为我不能更改参数。
发布于 2014-10-18 23:18:22
int没有基础,它们只是有价值。显示或用字符串表示的方式有基。因此,除非您从要转换的值的字符串表示开始,否则使用currBase是没有意义的。baseConverter被定义为返回一个字符串;因为它没有为该字符串传递空间,所以它必须分配它。baseConverter为其余数字提供一个字符串,并使用该字符串生成一个新字符串(需要分配该字符串),确保在完成递归调用时释放从递归调用中获得的字符串。https://stackoverflow.com/questions/26445488
复制相似问题