c++取小数点后两位
作者:野牛程序员:2023-07-18 10:26:41 C++阅读 2745
在C++中,可以使用流输出操作符 std::fixed 和 std::setprecision 来限制小数点后的位数。下面是一个示例:
#include <iostream>
#include <iomanip>
int main() {
double number = 3.14159;
std::cout << std::fixed << std::setprecision(2) << number << std::endl;
return 0;
}输出将是 3.14,其中 std::fixed 设置了小数点后的位数固定,std::setprecision(2) 设置了小数点后的位数为两位。
如果想要将结果存储在一个字符串中,可以使用 std::ostringstream:
#include <iostream>
#include <iomanip>
#include <sstream>
int main() {
double number = 3.14159;
std::ostringstream stream;
stream << std::fixed << std::setprecision(2) << number;
std::string result = stream.str();
std::cout << result << std::endl;
return 0;
}输出将是 "3.14",字符串 result 中包含了小数点后两位的结果。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c++ cout 都做了什么
- 下一篇:c++怎么保留小数位数
