c - 返回字符串的基本转换器

标签 c string recursion type-conversion

我有一个问题,我需要将从转换中收到的数字转换为字符串,然后返回它。问题是我不知道我如何尝试添加 use (char)(number + 48) 但它不起作用我尝试使用 itoa 函数,但同样的事情。但是该函数需要递归。 感谢您的帮助!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int itoc (int number, int base) {

    if(number == 0) return number;

    return (number % base) + 10 * itoc(number / base, base);
}


int main()
{   int a,b;
    scanf("%d%d", &number ,&base);
    printf("%d",itoc(number,base));
    return 0;
}

上面的版本是返回整数的版本。

最佳答案

您可以通过多种方式做到这一点。我的使用方式之一 sprintf 。在这里您需要对此进行一些更改,如下所示:

int main()
{
    int number,base;
    scanf("%d %d", &number ,&base);
    int ret=itoc(number,base);
    char str[32];
    sprintf(str, "%d", ret);//this convert it to string.
   // printf("%s\n",str);
    return 0;
}

关于c - 返回字符串的基本转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34116128/

相关文章:

c - 是否有必要在 IO 多路复用中使用非阻塞文件描述符?

python - 具有非重复字符的最长子串

objective-c - 字符串到 int 的转换返回 156112 而不是 objective-c 中的 1

algorithm - 迭代数独算法

javascript - 如何在 Yeoman 中使用 promises 进行递归提示?

Java递归斐波那契数列

c - 获取未知长度的字符串数组的长度

c++ -/usr/bin/ld : cannot find/usr/lib64/libasan. so.0.0.0 在 redhat 上

c - *argv++ 和 *argv-- 到达限制时的区别

string - 畸形二叉绳树