【问题标题】:How to make C++ cout not use scientific notation如何使 C++ cout 不使用科学计数法
【发布时间】:2011-07-09 21:08:20
【问题描述】:
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;
}
这是输出
巴斯安娜:3284.78 儿子 faiz:1784.78 儿子安娜:5069.55
Bas ana:7193.17 儿子 faiz:3908.4 儿子 ana:11101.6
Bas ana:15752 儿子 faiz:8558.8 儿子 ana:24310.8
Bas ana:34494.5 儿子 faiz:18742.5 儿子 ana:53237
巴斯安娜:75537.8 儿子 faiz:41043.3 儿子安娜:116581
Bas ana:165417 儿子 faiz:89878.7 儿子 ana:255295
Bas ana:362238 儿子 faiz:196821 儿子 ana:559059
Bas ana:793246 Son faiz:431009 Son ana:1.22426e+006
Bas ana:1.73709e+006 儿子 faiz:943845 儿子 ana:2.68094e+006
Bas ana:3.80397e+006 Son faiz:2.06688e+006 Son ana:5.87085e+006
我希望数字显示为精确数字而不是科学数字。我该怎么做?
【问题讨论】:
标签:
c++
double
cout
ostream
scientific-notation
【解决方案1】:
使用std::fixed流操纵器:
cout<<fixed<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl;
【解决方案2】:
如上所述,您可以使用std::fixed 来解决您的问题,如下所示:
cout << fixed;
cout << "Bas ana: " << x << "\tSon faiz: " << t << "\tSon ana: " << x+t <<endl;
但是,在您完成此操作后,每次您在项目中的任何位置打印float 或double 时,该数字仍会以这种固定的表示法打印。你可以通过使用将其转回
cout << scientific;
但如果您的代码变得更复杂,这可能会变得乏味。
这就是 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
您可以在the official docs 中找到有关 Boost 的 I/O 流状态保护程序的更多信息。
您可能还想查看Boost Format library,这也可以使您的输出更容易,尤其是在您必须处理国际化的情况下。但是,它不会帮助您解决这个特定问题。
【解决方案3】:
编码下一个语法:
std::cout << std::fixed << std::setprecision(n);
其中(n) 是十进制精度数。
这应该可以解决它。
P.s.:您需要#include <iomanip> 才能使用std::setprecision。
【解决方案4】:
在 C++20 中,您将能够使用 std::format 来执行此操作:
std::cout << std::format("Bas ana: {:f}\tSon faiz: {:f}\t"
"Son ana: {:f}\n", x, t, x + t);
输出:
Bas ana: 3284.776791 Son faiz: 1784.776791 Son ana: 5069.553581
Bas ana: 7193.172376 Son faiz: 3908.395585 Son ana: 11101.567961
...
这种方法的优点是它不会改变流状态。
同时你可以使用the {fmt} library,std::format是基于。 {fmt} 还提供了print 函数,使这更容易和更高效(godbolt):
fmt::print("Bas ana: {:f}\tSon faiz: {:f}\tSon ana: {:f}\n", x, t, x + t);
免责声明:我是 {fmt} 和 C++20 std::format 的作者。
【解决方案6】:
您可以使用 iostream 获得一整套格式化运算符。这是一个tutorial,可以帮助您入门。
【解决方案7】:
你可以这样使用fixed功能:
std::cout
或者您可以通过这种方式使用标准格式的 printf 函数,例如“12.12%f”:
printf ("number = %12.12f", float_number);
【解决方案8】:
你也可以在c++中使用printf来打印没有科学计数法的值。
您也可以使用cin 和cout 代替scanf 和printf,但是,如果您输入一百万个数字并打印一百万行,使用scanf 会更快和printf。
#include<stdio.h>
#include<math.h>
int main () {
double a = pow(2,99);
printf ("%lf\n",a);
return 0;
}
输出
633825300114114700748351602688.000000