我想对 float 进行四舍五入。
在Python中,我有:
round(x, 2) # 3.1415 -> 3.14
但是在c++中,我发现round
函数只能四舍五入到整数。
c++中有类似的方法吗?
最佳答案
您可以使用内置的舍入函数和一些科学记数法。
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
float x = 3.14159;
int val = 2;
x = round(x * pow(10, val)) / pow(10, val);
cout << x << endl;
return 0;
}
关于c++ - C++ 中是否有任何方法可以执行 round(a, n) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67513616/