2014-10-18 80 views
0

因此,即时创建递归函数以将数字从基数2-10转换为基数2-16时出现问题。我需要它返回一个字符串(显然,由于基数大于10)。使用递归将一个基数中的数字转换为另一个基数

这里是我的功能:

主要会这样称呼它:

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 
} 

我需要我的return语句和递归帮助呼叫。 我是否需要在函数中声明一个char数组,然后将从十六进制[r]得到的字符添加到它中?如果是这样,我该怎么做,因为我不能改变参数

+0

功能base10Converter的内容是什么 – 2014-10-18 23:17:36

回答

2
  • int s没有基地,他们只是有价值。你如何显示或用一个字符串表示,有基础。因此,除非以您想要转换的值的字符串表示形式开始,否则没有任何意义可用currBase,
  • baseConverter,被定义为它返回一个字符串;因为它没有传递该字符串的空间,所以它将不得不分配它。
  • 因此,对于递归的情况,你可以拨打baseConverter给你一个字符串给其余的数字,并用它来创建一个新的字符串(你需要分配),一定要取消分配当你完成后,你从递归调用中得到的字符串。
+0

感谢您的回复。对于你提到的第三点,我必须为我的函数(baseConverter)中的sting分配内存。然而,我想知道我是否返回了strncmp(hex [r],baseConverter(...));那会有用吗?如果不是,我将如何去做你的方式。 @Scott Hunter – mrquiksilver 2014-10-19 20:55:46

+0

strcat(hax [r],baseConverter(...));我的意思是 – mrquiksilver 2014-10-19 21:15:17

+0

'strcat'需要一个字符串来连接,这意味着需要在某个点分配字符串。此外,它假定您已经为连接分配了足够的空间。最后,'strcat'要求你连接一个字符串,而不是一个字符。 – 2014-10-20 00:32:09

相关问题