Ale*_*nko 14 c++ floating-point iostream
给定一个浮点类型的变量,如何在小数点后输出3位数,在C++中使用iostream?
das*_*ght 23
#include <iostream>
using namespace std;
int main () {
double f = 3.14159;
cout.setf(ios::fixed,ios::floatfield);
cout.precision(3);
cout << f << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这打印 3.142
mas*_*sk8 10
这个确实显示"13.141"
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
double f = 13.14159;
cout << fixed;
cout << setprecision(3) << f << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用iomanip标题获得固定数量的小数位(以及许多其他内容).例如:
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.141592653589;
std::cout << std::fixed << std::setprecision(2) << pi << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
将输出:
3.14
Run Code Online (Sandbox Code Playgroud)
请注意,fixed并且setprecision永久更改流,因此,如果要本地化效果,可以预先保存信息并在之后恢复:
#include <iostream>
#include <iomanip>
int main() {
double pi = 3.141592653589;
std::cout << pi << '\n';
// Save flags/precision.
std::ios_base::fmtflags oldflags = std::cout.flags();
std::streamsize oldprecision = std::cout.precision();
std::cout << std::fixed << std::setprecision(2) << pi << '\n';
std::cout << pi << '\n';
// Restore flags/precision.
std::cout.flags (oldflags);
std::cout.precision (oldprecision);
std::cout << pi << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
3.14159
3.14
3.14
3.14159
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40010 次 |
| 最近记录: |