【问题标题】:Division that rounds down rather than truncates四舍五入而不是截断的除法
【发布时间】:2017-01-29 11:28:51
【问题描述】:

我需要将除以某个正常数的实数值与最接近的较低整数对齐,而不管它们的符号如何。示例是(这里的反斜杠代表我想要的运算符)

21,5 \ 2 = 10
-21,5 \ 2 = -11
52,3 \ 2 = 26
-52,3 \ 2 = -27

是否有一个简短的操作员可以做到这一点?通常的“斜杠”(“/”)运算符在 C++ 中向零舍入(前段时间已成为标准)(例如 -52.6 / 2 = -26)。

【问题讨论】:

  • std::floor(a/b)
  • 不,c++中没有这样的运算符
  • 浮点除法根本不做任何舍入。 -52.6/2 在我的机器上是 -26.30000000000000071054273576010018587112427。
  • @Leon 这仅在 a 是浮点数时有效。我有时也有整数,无所谓。
  • 然后将整数转换为浮点数并使用std::floor

标签: c++ integer-division floor-division


【解决方案1】:

我们没有专门的操作符,但是我们可以做一个特殊的类型,重新定义合适的操作符:

#include <iostream>
#include <cmath>

template<class Integer>
struct RoundDown
{
    RoundDown(Integer v) : value_(v) {}

    operator Integer&() { return value_; }
    operator const Integer&() const { return value_; }

    template<class Other>
    RoundDown& operator/=(Other const& o)
    {
        value_ = Integer(std::floor(double(value_) / o));
        return *this;
    }

    Integer value_;
};

template<class IntegerL, class IntegerR>
auto operator/(RoundDown<IntegerL> l, IntegerR const& r)
{
    return l /= r;
}

int main()
{
    RoundDown<int> a { -57 };
    a /= 2;
    std::cout << a << '\n';
    std::cout << (a / 2) << '\n';
}

预期输出:

-29
-15

【讨论】:

  • OP 想要将实数除以整数,而不是整数除以整数。我认为一个函数会比一个类更直观。
  • @anatolyg 奇怪的是,即使模板参数被称为Integer,这个类也适用于实数。但是,我相信您对直观性的看法是正确的。
【解决方案2】:

std::floor 会解决你的问题。

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    // your code goes here
    float i = -21.5,b=2;
    int c = std::floor(i/b);
    cout << c << endl;

    i = 21.5,b=2;
    c = std::floor(i/b);
    cout << c << endl;

    int a = 11,b1 =2;
    c = std::floor(a/b1);
    cout << c << endl;

    a = -11;
    b =2.1;
    c = std::floor(a/b);
    cout << c << endl;
    return 0;
}

输出:

-11
10
5
-6

【讨论】:

    猜你喜欢
    • 2011-12-27
    • 1970-01-01
    • 2013-08-21
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多