在 printf() 中,宽度小于精度有什么意义?
What's the point of a width smaller than a precision in 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<
在第一种情况下,精度小于指定的宽度,实际上增加了一个前导空格。然而,当精度更高时,宽度似乎是多余的。
这样的格式有什么原因吗?
宽度格式指定符仅在打印数字的总宽度小于指定宽度时影响输出。显然,当精度设置大于或等于宽度时,这种情况永远不会发生。因此,宽度规格在这种情况下是无用的。
这是一篇来自MSDN;最后一句解释了。
不存在或较小的字段宽度不会导致字段的截断;如果转换结果比字段宽度宽,则字段展开以包含转换结果。
也许是程序员的错误?也许他们交换了%8.4f
或者他们实际上想要交换%12.8f
甚至%012.8f
参见示例代码:
#include <stdio.h>
int main()
{
printf("Seems unnecessary when decimals are greater: >%4.8f<n", 3.4567);
printf("Seems unnecessary when decimals are greater: >%8.4f<n", 3.4567);
printf("Seems unnecessary when decimals are greater: >%12.4f<n", 3.4567);
printf("Seems unnecessary when decimals are greater: >%012.4f<n", 3.4567);
return 0;
}
输出Seems unnecessary when decimals are greater: >3.45670000<
Seems unnecessary when decimals are greater: > 3.4567<
Seems unnecessary when decimals are greater: > 3.4567<
Seems unnecessary when decimals are greater: >0000003.4567<
可能只是猜测,但是:精度给小数一个长度,如果你有更多的小数,不会超过。同样,宽度可以防止你的号码占用比它应该占用的空间更少。如果你考虑某种带有数字的表,你只能在每行上的每列具有相同宽度时才能实现统一列,而不管它包含的数字是多少。
因此,在一些价格格式中需要精度,例如10.00€,而您总是需要2位小数。
对于你的特定行:我觉得你在这个特殊情况下的宽度说明符冗余。
相关文章:
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 从二进制流中读取时,将双精度变量的地址转换为 char* 意味着什么?
- 如果我在 C++ 中为 int 提供双精度,输入缓冲区中存储了什么?
- 标准库to_string(双精度)在 vs2015 中给出错误的值.有什么解决办法吗?
- 在C++中处理极其精确的浮点计算时,保持精度的标准方法是什么
- 为什么“从'x*'到'y'失去精度”是一个硬错误,什么是适合旧版代码的解决方案
- C++11 中的"auto var = {condition} ? 1 : 1.0"是什么类型?是双精度还是整数?
- 着色器中实现双精度cos()的结果是NaN,但在CPU上运行良好.出了什么问题
- 我可以从双精度中期待什么精度
- 如何将双精度数组从 VB6 传递到 VC++.这段代码有什么问题
- 为什么设置精度做错误?以及什么是设置精度
- 什么更贵?读取或比较整数,双精度
- 什么是精度
- 在 C/C++ 中从双精度到int64_t的隐式转换是什么
- 将int转换为void*会丢失精度,在需要的情况下解决方案是什么
- 使用C++样式转换以所需的精度执行表达式的正确方法是什么
- c++中对包含双精度类型数字的数组进行排序的最快方法是什么?
- c++的长双精度的范围是什么?
- 在 printf() 中,宽度小于精度有什么意义?
- 以二进制格式格式化 2D 双精度矩阵以读取 IDL 的最基本方法是什么?