向下舍入而不是截断的除法

时间:2016-09-21 09:33:37

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

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

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

是否存在执行此操作的短操作符?通常的“斜杠”(“/”)运算符在C ++中向零舍入(前一段时间是标准的)(例如-52.6 / 2 = -26)。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我们没有特殊的操作符,但我们可以创建一个特殊的类型,并重新定义适当的运算符:

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