如何使C++ cout不使用科学记数法

Yun*_*zel 59 c++ double cout scientific-notation ostream

double x = 1500;
for(int k = 0; k<10 ; k++){
    double t = 0;
    for(int i=0; i<12; i++){
        t += x * 0.0675;
        x += x * 0.0675;
    }
    cout<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl;      
}
Run Code Online (Sandbox Code Playgroud)

这个输出

Bas ana:3284.78 Son faiz:1784.78 Son ana:5069.55

Bas ana:7193.17 Son faiz:3908.4 Son ana:11101.6

Bas ana:15752 Son faiz:8558.8 Son ana:24310.8

Bas ana:34494.5 Son faiz:18742.5 Son ana:53237

Bas ana:75537.8 Son faiz:41043.3 Son ana:116581

Bas ana:165417 Son faiz:89878.7 Son ana:255295

Bas ana:362238 Son faiz:196821 Son ana:559059

Bas ana:793246 Son faiz:431009 Son ana:1.22426e + 006

Bas ana:1.73709e + 006 Son faiz:943845 Son ana:2.68094e + 006

Bas ana:3.80397e + 006 Son faiz:2.06688e + 006 Son ana:5.87085e + 006

我希望数字用精确数字显示而不是科学数字.我怎样才能做到这一点?

Tug*_*tes 80

使用std::fixed流操纵器:

cout<<fixed<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl;
Run Code Online (Sandbox Code Playgroud)


Mig*_*igi 20

如上所述,您可以使用std :: fixed来解决您的问题,如下所示:

cout << fixed;
cout << "Bas ana: " << x << "\tSon faiz: " << t << "\tSon ana: " << x+t <<endl;
Run Code Online (Sandbox Code Playgroud)

但是,在完成此操作后,每次在项目中的任何位置打印浮点数或双精度数时,该数字仍将以此固定表示法打印.您可以使用它将其转回

cout << scientific;
Run Code Online (Sandbox Code Playgroud)

但如果您的代码变得更复杂,这可能会变得乏味.

这就是为什么Boost创建了I/O流状态保护程序,它会自动将您正在使用的I/O流返回到函数调用之前的状态.你可以像这样使用它:

#include <boost/io/ios_state.hpp> // you need to download these headers first

{
    boost::io::ios_flags_saver  ifs( os );

    cout << ios::fixed;
    cout<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl;

} // at this bracket, when ifs goes "out of scope", your stream is reset
Run Code Online (Sandbox Code Playgroud)

您可以在官方文档中找到有关Boost的I/O Stream State Saver的更多信息.

您可能还想查看Boost格式库,它也可以使您的输出更容易,特别是如果您必须处理国际化.但是,它对这个特定问题无济于事.


小智 12

编码下一个语法:

std::cout << std::fixed << std::setprecision(n);
Run Code Online (Sandbox Code Playgroud)

其中(n)是十进制精度的数量。这应该解决它。

Ps:你需要#include <iomanip>为了使用std::setprecision.


vit*_*aut 6

在 C++20 中,您将能够使用它std::format来执行此操作:

std::cout << std::format("Bas ana: {:f}\tSon faiz: {:f}\t"
                         "Son ana: {:f}\n", x, t, x + t);
Run Code Online (Sandbox Code Playgroud)

输出:

std::cout << std::format("Bas ana: {:f}\tSon faiz: {:f}\t"
                         "Son ana: {:f}\n", x, t, x + t);
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是它不会改变流状态。

在此期间,您可以使用的{} FMT库std::format是基于。{fmt} 还提供了print使这更容易和更高效的功能(Godbolt):

fmt::print("Bas ana: {:f}\tSon faiz: {:f}\tSon ana: {:f}\n", x, t, x + t);
Run Code Online (Sandbox Code Playgroud)

免责声明:我是 {fmt} 和 C++20 的作者std::format