6

How do I perform a mod operation between two integers in C++?

4

6 回答 6

14

In c++, use % operator

More Help

于 2010-04-05T22:40:11.397 回答
14

C++ has the % operator, occasionally and misleadingly named "the modulus" operator. In particular the STL has the modulus<> functor in the <functional> header. That's not the mathematical modulus operator, mind you, because in modulus arithmetics a mod b by definition evaluates to a non-negative value for any value of a and any positive value of b. In C++ the sign of the result of a % b is implementation-defined if either of the arguments is negative. So, we would more appropriately name the % operator the remainder operator.

That said, if you truly want the mathematical modulus operator then you can define a function to do just that:

template<typename V>
V mod(const V& a, const V& b)
{
    return (a % b + b) % b;
}

So long as b is a positive value a call to the above function will yield a non-negative result.

于 2010-04-05T23:57:41.193 回答
10

As the other answers have stated, you can use the C++ % operator. But be aware that there's a wrinkle no one has mentioned yet: in the expression a % b, what if a is negative? Should the result of this operation be positive or negative? The C++ standard leaves this up to the implementation. So if you want to handle negative inputs portably, you should probably do something like r = abs(a) % b, then fix up the sign of r to match your requirements.

于 2010-04-05T23:09:22.617 回答
9

Like this: x=y%z

于 2010-04-05T22:41:24.407 回答
1

Using the modulus % operator :

int modulus_a_b = a % b;
于 2010-04-05T22:40:34.800 回答
1

if you use double variable, you should use;

double x;
double y;
double result = fmod(x, y);
于 2012-05-02T12:20:05.233 回答