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儿子法伊兹: 1784.78儿子安娜: 5069.55 巴斯安娜: 7193.17儿子法伊兹: 3908.4儿子安娜: 11101.6 巴斯安娜: 15752儿子法伊兹: 8558.8儿子安娜: 24310.8 巴斯安娜: 34494.5儿子法伊兹: 18742.5儿子安娜: 53237 巴斯安娜: 75537.8儿子法伊兹: 41043.3儿子安娜: 116581 巴斯安娜: 165417儿子法伊兹: 89878.7儿子安娜: 255295 巴斯安娜: 362238儿子法伊兹: 196821儿子安娜: 559059 巴斯安娜: 793246儿子法伊兹: 431009儿子安娜: 1.22426e+006 1.73709e+006儿子faiz: 943845儿子ana: 2.68094e+006 3.80397e+006儿子faiz: 2.06688e+006 Son ana: 5.87085e+006
我想用精确的数字来显示数字,而不是科学的数字。我该怎么做?
发布于 2011-03-06 17:19:47
使用std::fixed流机械手:
cout<<fixed<<"Bas ana: "<<x<<"\tSon faiz: "<<t<<"\tSon ana: "<<x+t<<endl;发布于 2011-03-06 20:13:36
如前所述,您可以使用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您可以在官方文件中找到更多关于Boost的I/O流状态保护程序的信息。
你可能也想看看Boost格式库,这也可以使你的输出更容易,特别是当你必须处理国际化。然而,对于这个特殊的问题,它不会对你有所帮助。
发布于 2018-11-27 08:55:40
编写下一个语法:
std::cout << std::fixed << std::setprecision(n);其中(n)是十进制精度的数字。这应该能解决问题。
P.s.:你需要#include <iomanip>才能使用std::setprecision。
https://stackoverflow.com/questions/5212018
复制相似问题