我不想重复使用 setprecision 和 fixed on cout。那么有什么办法可以只设置一个并将其用于代码块中的所有 cout 吗?'
int main()
{
double num1 = 1.00000, num2 = 2.00005;
cout **<< setprecision(5) << fixed <<** num1 << endl; <-- I do not to repeatedly set this.
cout **<< setprecision(5) << fixed** << num2 << endl;
}
下面我试过了,还是不行
int main()
{
double num1 = 1.00000, num2 = 2.00005;
cout.precision(5); cout.fixed; cout.showpoint; <-- Does not work
cout << num1 << endl << num2 << endl;
}
如有任何建议,我们将不胜感激。
最佳答案
举个例子:
#include <iostream>
int main () {
double f = 3.14159;
std::cout.unsetf ( std::ios::floatfield );
std::cout.precision(5);
std::cout << f <<endl;
std::cout.precision(10);
std::cout << f <<endl;
std::cout.setf( std::ios::fixed, std:: ios::floatfield );
std::cout << f <<endl;
return 0;
}
现在这给了我们一个输出:
3.1416
3.14159
3.1415900000
现在在你的例子中,代码应该是这样的:
#include <iostream>
int main () {
double num1 = 1.00000, num2 = 2.00005;
std::cout.unsetf ;
std::cout.precision(5);
std::cout << num1 <<endl;
std::cout << num2 <<endl;
return 0;
}
如果上述方法不起作用,我认为您将不得不重复并再次定义精度。
#include <iostream>
int main () {
double num1 = 1.00000, num2 = 2.00005;
std::cout.unsetf ;
std::cout.precision(5);
std::cout << num1 <<endl;
std::cout.precision(5);
std::cout << num2 <<endl;
return 0;
}
关于c++ - 如何为代码块中的所有 cout 设置精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66192791/