c - 以字符串为返回类型的函数

标签 c string function char return-type

我写了一个函数来整齐地打印一个浮点值。目前它直接在屏幕上输出它,但在我的代码的其他地方我需要将这个函数的结果存储在一个变量中作为字符串(或 char[])。有什么建议吗?

void printfFloat(float toBePrinted)
{
    uint32_t fi, f0, f1, f2;
    char c;
    float f = toBePrinted;

    if (f<0)
    {
        c = '-';
        f = -f;
    }
    else
    {
        c = ' ';
    }

    // integer portion.
    fi = (uint32_t) f;

    // decimal portion...get index for up to 3 decimal places.
    f = f - ((float) fi);
    f0 = f*10;   f0 %= 10;
    f1 = f*100;  f1 %= 10;
    f2 = f*1000; f2 %= 10;
    if(c == '-')
        printf("%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
    else
        printf("%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
}

这个函数的返回类型应该是什么?我想在最后做这样的事情:

char[32] buffer;
buffer = printfFloat(_myFloat);

最佳答案

What should be return type of this function?

C 没有 String 数据类型,因此您必须将缓冲区的地址作为参数传递:

char[32] buffer;
printfFloat(_myFloat, buffer);

您的函数将变为:

void printfFloat(float toBePrinted, char *buffer)
{
   ///rest of code

   if(c == '-')
    sprintf(buffer, "%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
   else
     sprintf(buffer, "%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
}

关于c - 以字符串为返回类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16913647/

相关文章:

C:包含动态分配成员的结构的范围?

c - 当我将指针递增 1 时,为什么不能访问字符串中的下一个元素?

c - 嵌套strtok_r() : succesive tokens contain parent delimiter

c - 如何检查矩阵反对角线上的项是否相同?

Javascript 无法在另一个函数内调用数组推送

c - c中与指针相关的段错误

系统 ("$BASHPID"的 C 函数)不工作

java - 安卓有bug吗? : String. substring(5).replace (“” , “” )//空字符串

c - strcat 的段错误

php - 从函数返回 "error"的最佳实践