C语言 printf 格式浮动带填充

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15268088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:37:02  来源:igfitidea点击:

printf format float with padding

cfloating-pointfloating-point-conversion

提问by nabulke

The following test code produces an undesired output, even though I used a width parameter:

即使我使用了宽度参数,以下测试代码也会产生不需要的输出:

int main(int , char* [])
{
    float test = 1234.5f;
    float test2 = 14.5f;

    printf("ABC %5.1f DEF\n", test);
    printf("ABC %5.1f DEF\n", test2);

    return 0;
}

Output

输出

ABC 1234.5 DEF   
ABC  14.5 DEF


How to achieve an output like this, which format string to use?

如何实现这样的输出,使用哪种格式字符串?

ABC 1234.5 DEF   
ABC   14.5 DEF

回答by NPE

The following should line everything up correctly:

以下应该正确排列所有内容:

printf("ABC %6.1f DEF\n", test);
printf("ABC %6.1f DEF\n", test2);

When I run this, I get:

当我运行这个时,我得到:

ABC 1234.5 DEF
ABC   14.5 DEF

The issue is that, in %5.1f, the 5is the number of characters allocated for the entire number, and 1234.5takes more than five characters. This results in misalignment with 14.5, which does fit in five characters.

问题是,在 中%5.1f5是为整个数字分配的字符数,并且1234.5需要超过五个字符。这会导致与 不对齐14.5,它确实适合五个字符。

回答by JasonD

You're trying to print something wider than 5 characters, so make your length specifier larger:

您正在尝试打印大于 5 个字符的内容,因此请增大长度说明符:

printf("ABC %6.1f DEF\n", test);
printf("ABC %6.1f DEF\n", test2);

The first value is not "digits before the point", but "total length".

第一个值不是“点之前的位数”,而是“总长度”。