38

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

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;
}

输出

ABC 1234.5 DEF   
ABC  14.5 DEF

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

ABC 1234.5 DEF   
ABC   14.5 DEF
4

2 回答 2

66

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

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

当我运行它时,我得到:

ABC 1234.5 DEF
ABC   14.5 DEF

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

于 2013-03-07T10:01:02.750 回答
16

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

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".

于 2013-03-07T10:01:38.637 回答