C - 打印出浮点值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15511276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:27:03  来源:igfitidea点击:

C - Printing out float values

c++cfloating-pointprecision

提问by FidelCashflo

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.30951the C program prints out 0.309510. More examples: C++: 0.0956439C: 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.

但是当 C++ 程序打印出来时,0.30951C 程序打印出0.309510. 更多示例:C++: 0.0956439C: 0.095644. 只要值是 7 位长,它似乎打印相同的结果,但如果它的 7 位数字更短,它会在末尾添加一个额外的 0。如果长度超过 7 位,则向下舍入为 6 位。我希望 C 结果与 C++ 程序匹配。任何帮助,将不胜感激。

Thanks.

谢谢。

Note: number is a float and number are read from a file.

注意:数字是一个浮点数,数字是从文件中读取的。

回答by Bob Kaufman

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

回答by Alex Chamberlain

Take advantage of the length and precision specifiers in C++ iostreams

利用长度和精度说明的在C ++iostream小号

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

回答by Sava Vrane?evi?

printf("%g\n", number); 

Will solve your problem, %lf is used for double, %f is used for float, and %g is used for float when you want to display all the decimal places and cut off zeros.

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