为什么模运算符(%)不同的C和Ruby之间的负整数的行为? [英] Why is the behavior of the modulo operator (%) different between C and Ruby for negative integers?

查看:167
本文介绍了为什么模运算符(%)不同的C和Ruby之间的负整数的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里运行在一些code。我试图 -40%3 。它给我的输出 2 。当我下进行同样的操作,我得到:

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 = (-40) % 3
printf("%d", i);

输出

-1

如何在内部进行取模运算两种语言?

How are both languages performing the modulo operation internally?

推荐答案

维基说:

由于两个正数 A (股息)和 N (中除数),一模n (简写为MOD n)是由n个 A的欧几里德除法的余。结果
  .... 当任 A N 是否定的,天真的定义分解和编程语言不同这些值是如何定义的

Given two positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n) is the remainder of the Euclidean division of a by n.
.... When either a or n is negative, the naive definition breaks down and programming languages differ in how these values are defined.

现在的问题是,为什么 -40%3 2 在Ruby或者换句话说什么是数学落后吗?


Now the question is why -40 % 3 is 2 in Ruby or in other words what is the mathematics behind it ?

让我们先从欧几里德师其中指出:

给定两个整数 A N ñ≠0 ,存在唯一的整数研究,使得 A = N * q + R 0≤为r | N | ,其中 | N | 表示的绝对值n

Given two integers a and n, with n ≠ 0, there exist unique integers q and r such that a = n*q + r and 0 ≤ r < |n|, where |n| denotes the absolute value of n.

现在注意商数的两个定义:

Now note the two definitions of quotient:

1 高德纳的描述其中商是由地板功能定义地板师 q =楼(A / N),其余的研究是结果

1. Donald Knuth described floored division where the quotient is defined by the floor function q=floor(a/n) and the remainder r is

这里的商()总是向下(即使它已经是负)圆润,其余的(研究)具有相同的符号作为除数

Here the quotient (q) is always rounded downwards (even if it is already negative) and the remainder (r) has the same sign as the divisor.

2 一些实现定义商作为

Q = SGN(一)地板(| A | / N)。 whre SGN 是符号函数

q = sgn(a)floor(|a| / n) whre sgn is signum function.

剩余(研究)具有相同的符号股息( A

and the remainder (r) has the same sign as the dividend(a).

现在一切都取决于


      
  • 如果实现去与定义 1 并定义楼(A / N )则值 40%3 1 -40%3 2 。这似乎是在这里为Ruby的情况。

  •   
  • 如果实现去与定义 2 并定义 SGN(一)楼(| A | / N),然后价值 40%3 1 -40%3 1 。这似乎是在这里为C和Java的情况。

  •   
  • If implementation goes with definition 1 and define q as floor(a/n) then the value of 40 % 3 is 1 and -40 % 3 is 2. Which here seems the case for Ruby.
  • If implementation goes with definition 2 and define q as sgn(a)floor(|a| / n), then the value of 40 % 3 is 1 and -40 % 3 is -1. Which here seems the case for C and Java.

这篇关于为什么模运算符(%)不同的C和Ruby之间的负整数的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆