0

I need to align real values divided by some positive constant to nearest lower integer, regardless of their sign. Example are ( here the backslash represents my desired operator)

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

Is there a short operator that does this ? the usual "slash" ( "/" ) operator rounds towards zero in C++ (that was made standard some time ago) (e.g. -52.6 / 2 = -26).

anatolyg
  • 26,506
  • 9
  • 60
  • 134
Charles
  • 988
  • 1
  • 11
  • 28

2 Answers2

2

std::floor will solve your problem.

#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;
}

Output:

-11
10
5
-6
Nishant Kumar
  • 2,199
  • 2
  • 22
  • 43
0

We don't have a special operator for it, but we could make a special type, and redefine appropriate operators:

#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';
}

Expected output:

-29
-15
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • OP wanted to divide real numbers by integers, not integers by integers. I think a function would be more intuitive for that than a class. – anatolyg Sep 21 '16 at 10:07
  • @anatolyg oddly enough, even though the template argument is called `Integer`, this class will work for real numbers too. However, I'm sure you're right about intuitiveness. – Richard Hodges Sep 21 '16 at 10:14