C++ 使用 << 和 double 时防止 ostream 中的科学记数法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2335657/
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 23:06:02  来源:igfitidea点击:

Prevent scientific notation in ostream when using << with double

c++iostreamscientific-notation

提问by DogDog

I need to prevent my double to print in scientific notation in my file,

我需要防止我的 double 在我的文件中以科学记数法打印,

when I do this

当我这样做时

outfile << X;

回答by davecoulter

To set formatting of floating variables you can use a combination of setprecision(n), showpointand fixed. In order to use parameterized stream manipulators like setprecision(n)you will have to include the iomanip library:

要设置浮动变量的格式,您可以使用setprecision(n),showpoint和的组合fixed。为了使用参数化的流操作器,setprecision(n)你必须包含 iomanip 库:

#include <iomanip>

setprecision(n): will constrain the floating-output to nplaces, and once you set it, it is set until you explicitly unset it for the remainder of the stream output.

setprecision(n): 将浮动输出限制到n位置,一旦你设置它,它就会被设置,直到你为流输出的其余部分明确取消它为止。

fixed: will enforce that all floating-point numbers are output the same way. So if your precision is set to 4 places, 6.2, and 6.20will both be output as:

fixed: 将强制所有浮点数以相同方式输出。因此,如果您的精度设置为 4 位,6.2, 和6.20都将输出为:

6.2000
6.2000

showpoint: will force the decimal portions of a floating-point variable to be displayed, even if it is not explicitly set. For instance, 4will be output as:

showpoint: 将强制显示浮点变量的小数部分,即使它没有明确设置。例如,4将输出为:

4.0

Using them all together:

一起使用它们:

outfile << fixed << showpoint;
outfile << setprecision(4);
outfile << x;

回答by Rozuur

Here's an example of usage http://cplus.about.com/od/learning1/ss/clessontwo_4.htm

这是一个使用示例 http://cplus.about.com/od/learning1/ss/clessontwo_4.htm

as per your question use

根据您的问题使用

  std::cout << std::fixed << a << std::endl;

回答by matiu

All the above answers were useful, but none directly answer the question.

以上所有答案都很有用,但没有一个直接回答问题。

outfile.setf(ios_base::fixed);
outfile << x;

I found the answer in @moogs link: http://www.cplusplus.com/reference/iostream/ios_base/fmtflags/

我在@moogs 链接中找到了答案:http://www.cplusplus.com/reference/iostream/ios_base/fmtflags/

Here's a demo program: http://ideone.com/FMxRp1

这是一个演示程序:http: //ideone.com/FMxRp1

回答by moogs