sprintf 输出 float 和 double 变量时最多输出多少个字符?
如果我这样做:
void printfloat(float number)
{
printf("%f", number);
}
并且
void printdouble(double number)
{
printf("%f", number);
}
每个函数可以输出的最大字符数是多少?
If I do this:
void printfloat(float number)
{
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过使用 MS Visual Studio 10 进行测试,得到的字符串为 811,
当然更长的字符串可能具有更大的精度值。
但保留“%f”,“\0”的最大输出字符数为 317 + 1。
因此,对于可移植代码:
函数 printfloat(float number) 唯一参数“number”是一个浮点型且仅限于浮点型范围,在传递给 sprintf() 时将转换为双精度型。因此它的最大值是FLT_MAX。因此,'\0' 的最大输出字符数为 47 + 1。
Via testing, using MS Visual Studio 10, a string of 811 resulted from
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:
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'.
结论:
我无法让 snprintf 告诉我字符串有多大,并且我希望使代码尽可能独立于编译器。所以这是我想出的解决方案。
%g 以科学记数法输出数字,这严重限制了字符数。我选择了一个足够大的缓冲区来容纳可能输出的任何内容。我唯一的编译器依赖是 sprintf_s。
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.
%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.
通过 wc -c 管道传输的快速测试程序显示浮点型有 47 个字符,双精度型有 317 个字符。程序:
请注意,您可以使用 snprintf 将输出限制为 n 个字符。
A quick test program piped through wc -c shows 47 characters for float, and 317 for double. The program:
Note that you can use snprintf to limit the output to n chars.