簡體   English   中英

函數使用字符串作為返回類型

[英]Function with string as 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);

這個函數應該返回什么類型?

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);
}

看看asprintf ,它會為你分配一個緩沖區並填充它。

char *printfFloat(float toBePrinted)
{
    uint32_t fi, f0, f1, f2;
    char c;
    char *ret = NULL;
    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 == '-')
        asprintf(&ret, "%c%ld.%d%d%d", c, fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
    else
        asprintf(&ret, "%ld.%d%d%d", fi, (uint8_t) f0, (uint8_t) f1, (uint8_t) f2);
    return ret;
}

主要:

#include <stdio.h>
int main()
{
   char *ret = printfFloat(42.42);
   puts(ret); // print ret
   free(ret);
   return 0;
}

您可以使用sprintf 函數

char buffer[32];
sprintf(buffer, "%f", your_float);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM