Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulo Operator (%) gives divergent results

Tags:

c++

c++11

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!

like image 948
Grundkurs Avatar asked Mar 26 '15 01:03

Grundkurs


People also ask

What does modulus operator (%) do?

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.

What will be the output of the modulus (%) operator?

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.

What types does the mod (%) work on?

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.

What is the symbol of modulus operator?

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 + , - , / , * , ** , // .


1 Answers

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.

like image 181
chris Avatar answered Oct 28 '22 14:10

chris