gpt4 book ai didi

c - 为什么 C 和 Ruby 中负整数的模运算符 (%) 的行为不同?

转载 作者:数据小太阳 更新时间:2023-10-29 08:27:14 28 4
gpt4 key购买 nike

我在 here 中运行一些代码.我试过 -40 % 3。它给了我输出 2。当我在 C 中执行相同的操作时,我得到:

int i = (-40) % 3
printf("%d", i);

输出是

-1

这两种语言如何在内部执行模运算?

最佳答案

Wiki说:

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 % 32在 Ruby 中,或者换句话说,背后的数学原理是什么?

让我们从Euclidean division开始其中指出:

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.

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

  1. Donald Knuth描述了下限除法,其中商由下限函数定义 q=floor(a/n)和其余的 r是:

enter image description here

此处商 ( q ) 始终向下舍入(即使它已经是负数),余数 ( r ) 与除数的符号相同

  1. 一些实现将商定义为:

q = sgn(a)floor(|a| / n)哪里sgn是符号函数。

余数 ( r ) 与股息 ( a ) 的符号相同

现在一切都取决于q :

  • 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 - 为什么 C 和 Ruby 中负整数的模运算符 (%) 的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24074869/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com