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

后端 未结 3 395
孤城傲影
孤城傲影 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:58

    In the ruby implementation, when the numerator is negative and the denominator is positive, the question that the modulo operator answers is, "What is the smallest positive number that when subtracted from the numerator, allows the denominator to divide evenly into the result?"

    In all implementations, when the numerator and denominator are both positive, the question being answered is, "What is the smallest positive number that when subtracted from the numerator, allows the denominator to divide evenly into the result?"

    So you can see that the ruby implementation is consistently answering the same question, even if the result is non-intuitive at first.

提交回复
热议问题