将int转换为带小数的字符串

标签 c string int decimal

出于各种原因,我想用 C 编写自己的函数,将 int 转换为小数字符串,就像 sprintf 一样。

例子:

    int number = 254;
    char string[10];
    sprintf(string, "%d", number);

在我要编写的函数之后的字符串应该如下所示:

    [0] 2
    [1] 5
    [2] 4
    [3] '\0'

为了进一步说明,我想编写将 int 实际转换为 char 字符串的程序。我不想使用 sprintf 或 itoa 等来做到这一点。我想知道它是如何完成的,并且能够自己编程并对其进行小的调整。

补充说明: 我不想使用 itoa 或 sprintf,但大部分都是自己编写的。

最佳答案

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

int i2a(char *s, int n){
    div_t qr;
    int pos;

    if(n == 0) return 0;

    qr = div(n, 10);
    pos = i2a(s, qr.quot);
    s[pos] = qr.rem + '0';
    return pos + 1;
}

char* my_itoa(char *output_buff, int num){
    char *p = output_buff;
    if(num < 0){
        *p++ = '-';
        num *= -1;
    } else if(num == 0)
        *p++ = '0';
    p[i2a(p, num)]='\0';
    return output_buff;
}

int main(void){
    int number = -254;
    char string[12];
    printf("%s", my_itoa(string, number));
    return 0;
}

关于将int转换为带小数的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16282047/

相关文章:

c - Mac OS X 上的 Valgrind 错误 printf a double

c - 二进制补码 stm32 c

python - 如何检查字符串中的字符是否为字母? (Python)

字符串处理

java - 如何将 (00s...11s) 的数组,每个字符的二进制表示,转换为 char 的字符串

c++ - OpenCV undefined reference 库中我自己的方法

python - Swig C 到 Python ImportError : undefined symbol

将 char 转换为 1 个字符的空终止字符串

c - 如何测试下面的代码?如果我为声明为 'unsigned int' 的变量提供有符号整数,会发生什么?

mysql - 将 MySQL 结果转换为 int (C++)