C: printf 一个浮点值

我想打印一个浮点数值,它有2个整数位和6个小数位后的逗号。如果我只使用 printf("%f", myFloat),我会得到一个截断的值。

我不知道这是否总是发生在 C 语言中,或者只是因为我使用 C 语言作为微控制器(确切地说是 CCS) ,但是在参考文献中它告诉 %f得到的就是这个: 一个截断的浮点数。

如果我的浮点数是 44.556677,我将打印出 "44.55",只有前两个小数位。

所以问题是... ... 我怎样才能打印我的6位数字(只打印其中的6位数字,以防万一后面还有零之类的数字) ?

721928 次浏览

You can do it like this:

printf("%.6f", myFloat);

6 represents the number of digits after the decimal separator.

printf("%.<number>f", myFloat) //where <number> - digit after comma

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

You need to use %2.6f instead of %f in your printf statement

Use %.6f. This will print 6 decimals.

printf("%9.6f", myFloat) specifies a format with 9 total characters: 2 digits before the dot, the dot itself, and six digits after the dot.

printf("%0k.yf" float_variable_name)

Here k is the total number of characters you want to get printed. k = x + 1 + y (+ 1 for the dot) and float_variable_name is the float variable that you want to get printed.

Suppose you want to print x digits before the decimal point and y digits after it. Now, if the number of digits before float_variable_name is less than x, then it will automatically prepend that many zeroes before it.

Try these to clarify the issue of right alignment in float point printing

printf(" 4|%4.1lf\n", 8.9);
printf("04|%04.1lf\n", 8.9);

the output is

 4| 8.9
04|08.9