C-打印浮点值 [英] C - Printing out float values
问题描述
我有一个C ++程序,它接受值并打印出这样的值:
I have a C++ program that takes in values and prints out values like this:
getline(in,number);
cout << setw(10) << number << endl;
我有一个等效的C程序,它接受值并像这样打印:
I have an equivalent C program that takes in values and prints out like so:
fscanf(rhs, "%e", &number);
printf("%lf\n", number);
但是在C ++程序打印出 0.30951
的同时,C程序打印出 0.309510
.更多示例:C ++: 0.0956439
C: 0.095644
.只要该值是7位数字,它看起来就可以打印出相同的结果,但是如果它的7位数字较短,它将在末尾添加一个额外的0.如果长度超过7位,则四舍五入为6位.我希望C结果与C ++程序匹配.任何帮助将不胜感激.
But while the C++ program prints out, 0.30951
the C program prints out 0.309510
. More examples: C++: 0.0956439
C: 0.095644
. It seems to print the same results as long as the value is 7 digits long, but if its shorter the 7 digits, it adds an extra 0 at the end. And if its longer than 7 digits, it rounds down to 6 digits. I would like the C results to match the C++ program. Any help would be appreciated.
谢谢.
注意:数字是浮点数,数字是从文件中读取的.
Note: number is a float and number are read from a file.
推荐答案
在C格式的打印语句中利用长度和精度说明符:
Take advantage of the length and precision specifiers in C formatted print statements:
printf( "%6.4lf", number );
在一个宽度为六个字符的单元格"中打印四个小数位.
Prints four decimal places in a "cell" six characters wide.
您可以使用通配符来指定长度或精度,以在运行时提供该值:
You can use a wildcard character for either length or precision to provide that value at runtime:
int precision = 4;
printf( "%6.*lf", precision, number );
这篇关于C-打印浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!