Given this Example:
std::vector<int> numbers = {5,6,7}; //size is 3
int i = -1;
std::cout << i % 3 <<"\n"; // output: -1
std::cout << i % numbers.size() << "\n"; // output: 0
basically in both statements im processing -1 % 3 but the compiler outputs different numbers. I don't understand this outcome, maybe someone can explain it to me.
edit: as @Chris,@Keith Thompson @AnT suggested the snippet
std::cout << std::numeric_limits<std::size_t>::max() % 3 <<"\n"; //output: 0
std::cout << i % numbers.size() << "\n"; // output: 0
prints the expected output. Thanks for the helpful advice to everyone!
The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.
The modulo division operator produces the remainder of an integer division. produces the remainder when x is divided by y. Return Value: If y completely divides x, the result of the expression is 0.
3) modulus operator is not just applicable to integral types e.g. byte, short, int, long but also to floating-point types like float and double. 4) You can also use the remainder operator to check if a number is even or odd, or if a year is leap year.
The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem. The modulo operator is considered an arithmetic operation, along with + , - , / , * , ** , // .
i % 3
is what you expect and, since C++11, has defined semantics rather than having an implementation-defined (if I recall correctly) result.
numbers.size()
has an unsigned type (std::size_t
). Assuming size_t
is as big as int
or bigger, i
is converted to the same unsigned type before the operation is performed. The value i
gets will be the maximum value for that type, which looks to be divisible by 3 for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With