+ 5
Who can explain the C++ modulo operator logic: why, for example, 3 % 4 is equal to 3?
Why is the modulo operator different in C++ from mathematics? Code for checking: #include <iostream> using namespace std; int main() { cout << 25 % 60 << endl; return 0; } Output: 25
7 Réponses
+ 6
well the modulus operator finds the remainder.
ex:
3 ÷ 4
4 does not divide three into a whole number,
it leaves remainder 3.
+ 6
25 ÷ 60
leaves remainder
25
+ 6
Thank you for your answers, but I know what output is going to be generated in certain cases.
What I am actually asking about is the LOGIC: why?.. why not 0?...
+ 6
@ZyuZick
if there is no remainder the output is zero.
% gives the remainder after dividing.
+ 1
the modulo operator(%) is used to get the remainder, but in a case where the number being divided is lesser than the one dividing it, then the number being divided, becomes ur answer. e. g
8%2 = 0
8%3 = 2 (becus the remainder is 2)
3%8 = 3 (explanation above)
+ 1
@Zyuzick
because
n%m == n (while n<m) [ n,m > 0]
n%m == 0 (only when m == n and m is a factor of n)
0
3%4 means b in 3=4×a + b