
在C++中,我们可以使用setprecision(n)函数来控制输出结果的小数位数。这个函数定义在<iomanip>头文件中,它可以与fixed函数一起使用,以确保小数点后的位数固定。以下是一些常见的用法示例:
1. 使用setprecision(n)和fixed函数
using namespace std;
int main() {
double num = 3.1415926;
cout << fixed << setprecision(2) << num << endl; // 输出: 3.14
return 0;
}
2. 不使用fixed函数
using namespace std;
int main() {
double num = 3.1415926;
cout << setprecision(2) << num << endl; // 输出: 3.1
return 0;
}
3. 使用printf函数(C风格)
int main() {
float num = 3.1415926;
printf("%.2f\n", num); // 输出: 3.14
return 0;
}
4. 使用stringstream类
using namespace std;
int main() {
double num = 3.1415926;
stringstream ss;
ss << fixed << setprecision(2) << num;
cout << ss.str() << endl; // 输出: 3.14
return 0;
}
5. 手动计算
using namespace std;
int main() {
double num = 3.1415926;
int precision = 2;
num = round(num * pow(10, precision)) / pow(10, precision);
cout << num << endl; // 输出: 3.14
return 0;
}
以上代码示例展示了在C++中保留输出结果小数的不同方法。根据具体需求,可以选择合适的方法来控制输出的小数位数。
