【问题标题】:Converting a number in one base to another base using recursion使用递归将一个基数中的数字转换为另一个基数
【发布时间】:2014-12-14 05:53:17
【问题描述】:

所以我在创建递归函数以将数字从基数 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 
}

我的 return 语句和递归调用需要帮助。 我是否需要在函数中声明一个字符数组,然后将我从 hex[r] 获得的字符附加到它上面?如果是这样,我该怎么做,因为我无法更改参数

【问题讨论】:

  • 函数base10Converter的内容是什么

标签: c string recursion base-conversion


【解决方案1】:
  • ints 没有基础,它们只有值。你如何显示,或用字符串表示,有基础。因此,currBase 是没有意义的,除非您从要转换的值的字符串表示开始。
  • baseConverter, 被定义为返回一个字符串;由于没有为该字符串传递空间,因此必须分配它。
  • 因此,对于递归的情况,您可以调用baseConverter 为您提供一个字符串作为其余数字,并使用它来创建一个 new 字符串(您需要分配),确保在完成后释放从递归调用中获得的字符串。

【讨论】:

  • 感谢您的回复。对于您提到的第三点,我必须为我的函数(baseConverter)中的一个字符串分配内存。但是我想知道我是否返回了 strncmp(hex[r], baseConverter(...));那行得通吗?如果不是,我将如何按照你的方式去做。 @斯科特·亨特
  • strcat(hax[r], baseConverter(...));我的意思是
  • strcat 需要一个字符串来连接,这意味着需要在某个时候分配字符串。此外,它假定您已为串联分配了足够的空间。最后,strcat 要求您连接一个字符串,而不是一个字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-22
  • 1970-01-01
  • 2022-12-21
  • 1970-01-01
相关资源
最近更新 更多