c++如何保留两位小数
lewis
2017-08-10
21次阅读
在C++中,可以使用iomanip头文件中的setprecision函数来控制输出的小数位数。以下是一个示例代码:
#include <iostream>
#include <iomanip>
int main() {
double number = 3.1415926;
std::cout << std::fixed << std::setprecision(2) << number << std::endl;
return 0;
}
输出结果为:
3.14
在代码中,std::fixed用于指定以固定的小数位数输出,std::setprecision(2)用于设置小数位数为2。然后,通过std::cout输出保留两位小数的结果。

发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。