微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 宽度小于printf()的精度是多少?

我看到一些代码看起来像:
fprintf(fd,"%4.8f",ptr->myFlt);

这些天我没有使用C,我阅读了关于printf及其同类的文档,并了解到在这种情况下4是“宽度”,8是“精度”.宽度定义为输出占用的最小空间数,如果需要,填充带前导空格.

既然如此,我无法理解像“%4.8f”那样的模板是什么意思,
因为点之后的8(必要时填零)小数点已经确保满足并超过了4的宽度.所以,我在Visual C中写了一个小程序

// Formatting width test

#include "stdafx.h"

int _tmain(int argc,_TCHAR* argv[])
{
    printf("Need width when decimals are smaller: >%4.1f<\n",3.4567);
    printf("Seems unnecessary when decimals are greater: >%4.8f<\n",3.4567);
    printf("Doesn't matter if argument has no decimal places: >%4.8f<\n",(float)3);

    return 0;
}

它给出了以下输出

Need width when decimals are smaller: > 3.5<
Seems unnecessary when decimals are greater: >3.45670000<
Doesn't matter if argument has no decimal places: >3.00000000<

在第一种情况下,精度小于指定的宽度,实际上增加了前导空格.然而,当精度更高时,宽度似乎是多余的.

是否有这样的格式的原因?

解决方法

如果打印数字的总宽度小于指定宽度,则宽度格式说明符仅影响输出.显然,当精度设置为大于或等于宽度时,这种情况永远不会发生.因此,在这种情况下宽度规格是无用的.

Here’s来自MSDN的一篇文章;最后一句解释了它.

A nonexistent or small field width does not cause the truncation of a field; if the result of a conversion is wider than the field width,the field expands to contain the conversion result.

原文地址:https://www.jb51.cc/c/119224.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐