Why is the behavior of the modulo operator (%) different between C and Ruby for negative integers?

后端 未结 3 397
孤城傲影
孤城傲影 2020-12-01 20:27

I was running some code in here. I tried -40 % 3. It gives me the output 2. when I performed the same operation in C, I get:

int i          


        
3条回答
  •  心在旅途
    2020-12-01 20:45

    In Java and C, the result of the modulo operation has the same sign as the dividend, hence -1 is the result in your example.

    In Ruby, it has the same sign as the divisor, so +2 will be the result according to your example.

提交回复
热议问题