开发者

What are the maximum numbers of characters output by sprintf when outputting float and double variables?

If I do this:

void printfloat(float numb开发者_JAVA百科er)
{
    printf("%f", number);
}

and

void printdouble(double number)
{
    printf("%f", number);
}

What is the maximum number of characters that can be output by each function?


Via testing, using MS Visual Studio 10, a string of 811 resulted from

sprintf(buf, "%.*f", 500, -DBL_MAX);

Certainly longer strings are possible with larger precision values.

But staying with "%f", the maximum number of characters output is 317 + 1 for the '\0'.
So for portable code:

#include <float.h>
#include <stdio.h>

    char buf[1/*'-'*/ + (DBL_MAX_10_EXP+1)/*308+1 digits*/ + 1/*'.'*/ + 6/*Default? precision*/ + 1/*\0*/];
    sprintf(buf, "%f", -DBL_MAX);

The function printfloat(float number) lone parameter "number", being a float and limited to a float's range, is converted to a double in passing to sprintf(). It's maximum value is thus FLT_MAX. So the maximum number of characters output is 47 + 1 for the '\0'.

    char buf[1/*'-'*/ + (FLT_MAX_10_EXP+1)/*38+1 digits*/ + 1/*'.'*/ + 6/*Default? precision*/ + 1/*\0*/];
    sprintf(buf, "%f", -FLT_MAX);


Conclusion:

I was unable to get snprintf to tell me how big the string would be, and I want to keep the code as compiler-independent as possible. So here is the solution I came up with.

char numstr[50];
sprintf_s(numstr, "%g", *value);
m_stringRepresentation += numstr;

%g outputs the number in scientific notation, which severely limits the number of characters. I picked a buffer large enough to contain anything that might output. My only compiler-dependency is on sprintf_s.


A quick test program piped through wc -c shows 47 characters for float, and 317 for double. The program:

#include <stdio.h>
#include <float.h>

int main(void) {
        printf("%f", -DBL_MAX);
}

Note that you can use snprintf to limit the output to n chars.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜