如何在 C++ 中重现 python3 的 round 函数

问题描述 投票:0回答:1

使用 python3

round(x, n)
函数,我们可以将浮点数四舍五入到固定的小数位。例如
round(2.675, 2) = 2.67
round(2.685, 2) = 2.69
。我如何在 C++ 中实现这样的功能?
round(x*100.0)/100.0
使用 python3 给出不同的结果。 Python的结果和
printf("%.2f", 2.675)
一样。因此,一种方法是使用
sprintf
函数将结果存储在 char 数组中。然后将 char 数组转换回 double。但这非常慢。有没有更好的办法?谢谢。

我在想既然

printf
函数可以自动做舍入,有没有办法直接将
printf
函数舍入结果存储到double变量中?

编辑:我想解释一下为什么我需要四舍五入到小数点后两位。因为我在把同事的python程序翻译成C++。在 python 程序中,他使用 round(2.675, 2)=>2.67。并且 C++ 中没有相应的轮函数来给出完全相同的结果。如果回合结果相差 0.01(如果 cpp_round(2.675, 2)=>2.68),它将在计算中触发一个完全不同的过程。

可能让同事改成自己写的round函数更简单。但是由于他的程序正在使用中,他很难进行此更改。

c++ python-3.x printf decimal rounding
1个回答
0
投票

您需要首先创建一个输出缓冲区,然后使用字符串标准库将 char 数组转换为双精度数:

#include <iostream>
#include <string>

double round(double val) {
    char buffer[100];
    snprintf(buffer, sizeof(buffer), "%.2f", val);
    return std::stod(buffer);
}

int main()
{
    double rounded = round(3.14159);
    std:: cout << rounded;
}
© www.soinside.com 2019 - 2024. All rights reserved.