简体   繁体   English

C - 打印浮动值

[英]C - Printing out float values

I have a C++ program that takes in values and prints out values like this: 我有一个C ++程序,它接受值并打印出这样的值:

getline(in,number);
cout << setw(10) << number << endl;

I have an equivalent C program that takes in values and prints out like so: 我有一个等价的C程序,它接受值并打印出来像这样:

fscanf(rhs, "%e", &number);
printf("%lf\n", number);

But while the C++ program prints out, 0.30951 the C program prints out 0.309510 . 但是当C ++程序打印出来时, 0.30951 C程序打印出0.309510 More examples: C++: 0.0956439 C: 0.095644 . 更多示例: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. 只要值为7位数,它似乎打印相同的结果,但如果它的7位数字较短,则在末尾添加额外的0。 And if its longer than 7 digits, it rounds down to 6 digits. 如果超过7位数,它会向下舍入到6位数。 I would like the C results to match the C++ program. 我希望C结果与C ++程序相匹配。 Any help would be appreciated. 任何帮助,将不胜感激。

Thanks. 谢谢。

Note: number is a float and number are read from a file. 注意:number是一个浮点数,从文件中读取数字。

Take advantage of the length and precision specifiers in C formatted print statements: 利用C格式打印语句中的长度和精度说明符:

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

Take advantage of the length and precision specifiers in C++ iostream s 利用C ++ iostream中的长度和精度说明符

std::cout.precision(4);
std::cout << std::setw(10) << number << "\n";
printf("%g\n", number); 

将解决您的问题,%lf用于double,%f用于float,%g用于float,当您想显示所有小数位并切断零时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM