%之后会怎样?
我已经搜索了一下,但没有得到一个特别直接的答案。在C语言中(我猜是C ++),当使用printf
时,如何确定%之后的值?例如:
double radius = 1.0; double area = 0.0; area = calculateArea( radius ); printf( "%10.1f %10.2\n", radius, area );
我直接从一本有关C语言的书中举了这个例子。这对我完全没有意义。我们在哪里想出" 10.1f"和" 10.2f"?有人可以解释一下吗?
解决方案
回答
man 3 printf
在Linux系统上将为我们提供所需的所有信息。我们还可以在线找到这些手册页,例如在http://linux.die.net/man/3/printf
回答
http://en.wikipedia.org/wiki/Printf#printf_format_placeholders是Wikipedia对printf中格式占位符的参考。 http://www.cplusplus.com/reference/clibrary/cstdio/printf.html也有帮助
基本上是一种简单的形式,即%[width]。[precision] [type]。宽度使我们可以确保要打印的变量至少具有一定的长度(对于表格等有用)。精度允许我们指定打印数字的精度(例如,小数位等),并通知C / C ++我们给定的变量是什么(字符,整数,双精度等)。
希望这可以帮助
更新:
为了阐明示例,请执行以下操作:
printf( "%10.1f %10.2\n", radius, area );
%10.1f(指第一个参数:radius)表示使其长度为10个字符(即,用空格填充),并以浮点数形式打印,并保留小数点后一位。
%10.2(参考第二个参数:area)表示使其长10个字符(如上所述),并用两位小数打印。
回答
10.1f表示我们要显示一个带小数点后一位的浮点数,显示的数字应为10个字符长。
回答
简而言之,%后面的值告诉printf
如何解释(或者输出)以后出现的所有变量。在示例中," radius"被解释为浮点数(即" f"),而" 10.1"给出了有关在打印时使用多少小数位的信息。
有关可与printf一起使用的所有修饰符的更多详细信息,请参见此链接。
回答
手册页包含所需的信息。阅读上面的内容:
printf( "%10.2f", 1.5 )
这将打印:
1.50
然而:
printf("%.2f", 1.5 )
印刷:
1.50
注意两者的合理性。
相似地:
printf("%10.1f", 1.5 )
将打印:
1.5
之后的任何数字。是我们要打印的精度。之前的任何数字。是距左边距的距离。
回答
10.1f表示宽度为10个字符的浮点,小数点后第一位。
如果数字少于10位,则用空格填充。
10.2f相同,但小数点后有2位。
我们具有以下基本类型:
%d - integer %x - hex integer %s - string %c - char (only one) %f - floating point (float) %d - signed int (decimal) %i - signed int (integer) (same as decimal). %u - unsigned int %ld - long (signed) int %lu - long unsigned int %lld - long long (signed) int %llu - long long unsigned int
编辑:@Eli的响应(man 3 printf)中列出了其他几个。
回答
10.1f means floating point with 1 place after the decimal point and the 10 places before the decimal point. If the number has less than 10 digits, it's padded with spaces. 10.2f is the same, but with 2 places after the decimal point.
在从Unix到Rails Migrations的每个系统上,情况并非如此。 @robintw最好地表达了这一点:
Basically in a simple form it's %[width].[precision][type].
即,不是"小数点前10位",而是"包括小数点前和后10位"。
回答
其他人没有提出的一个问题是double是否等于float。在某些系统上,与float相比,double需要使用不同的格式说明符。尤其是因为传递的参数大小可能不同。
%f - float %lf - double %g - double