printf 浮点值的字符串格式
我有一个关于使用 printf 的问题。
char str[8];
float val = 2.334563;
sprintf(str, format, val);
printf("val = %s.\n", str);
val = -23.34563;
sprintf(str, format, val);
printf("val = %s.\n", str);
val = -0.02334563;
sprintf(str, format, val);
printf("val = %s.\n", str);
val = 233;
sprintf(str, format, val);
printf("val = %s.\n", str);
预期输出如下:
val = +2.3345
val = -23.345
val = -0.0233
val = +233.00
我需要什么格式字符串?感谢您的关注。
I have a question about using printf.
char str[8];
float val = 2.334563;
sprintf(str, format, val);
printf("val = %s.\n", str);
val = -23.34563;
sprintf(str, format, val);
printf("val = %s.\n", str);
val = -0.02334563;
sprintf(str, format, val);
printf("val = %s.\n", str);
val = 233;
sprintf(str, format, val);
printf("val = %s.\n", str);
The expected output follows:
val = +2.3345
val = -23.345
val = -0.0233
val = +233.00
What format string do I need for that? Thank you for your attention.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
老好人
%f
怎么了what happened to the good old
%f
例子
example
以下(几乎)可以满足您的要求。请注意,我将
str
数组中的字符数从 7 更改为 8;由于所有输出字符串都包含 7 个字符,因此sprintf
执行的 NULL 终止将导致缓冲区溢出。我的结果和你的结果之间的唯一区别是
sprintf
执行的舍入。 AFAIK,解决这个问题的唯一方法是使用floor
预先截断要打印的数字;例如,要打印 2 位数字而不进行舍入float f = Floor( 1.8888 * 100 ) / 100;
输出:
The following (almost) does what you want. Note that I changed the number of characters in the
str
array from 7 to 8; since all of your output strings contain 7 characters the NULL termination performed bysprintf
will cause buffer overflow otherwise.The only difference between my results and yours is the rounding performed by
sprintf
. AFAIK, the only way to get around this is to pre-truncate the number you want to print usingfloor
; for example, to print 2 digits without roundingfloat f = floor( 1.8888 * 100 ) / 100;
Output:
使用
snprintf()
将字符串截断为 8 个字符,包括\0
格式字符串:
代码:
输出:
use
snprintf()
to truncate string at exactly 8 characters including\0
Format string:
Code:
Output:
我唯一能想到的是:
在这种情况下,您需要传递一个附加参数(
places_past_decimal
),它是数字中剩余的未使用的位数在号码的左侧。The only thing that I can come up with is as follows:
In this case, you will need to pass an additional argument (
places_past_decimal
) which is the number of digits remaining in the number that aren't used by the left side of the number.