在 C++ 中有什么方法可以做 round(a, n) 吗?

时间:2021-05-13 03:44:23

标签: c++

我想对浮点数进行四舍五入。

在python中,我有:

round(x, 2)  # 3.1415 -> 3.14

但在 C++ 中,我发现 round 函数只能舍入为整数。

c++中是否有类似的方法?

2 个答案:

答案 0 :(得分:1)

AFAIK 标准库没有提供这样的功能,但推出自己的功能应该不会太难:

#include <iostream>
#include <cmath>

// fast pow for int, credit to https://stackoverflow.com/a/101613/13188071
int ipow(int base, int exp)
{
    int result = 1;
    while (true)
    {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        if (exp == 0)
            break;
        base *= base;
    }

    return result;
}

double round_prec(double n, int prec)
{
    return std::round(n * ipow(10, prec)) / ipow(10, prec);
}

int main()
{
    std::cout << round_prec(3.1415, 2) << '\n';
}

输出:

3.14

然而,这有点迂回,可能有我不知道的更好的方法。

答案 1 :(得分:1)

您可以使用内置的舍入函数和一些科学记数法。

#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;
}
相关问题