为什么模数在不同的编程语言中有所不同? [英] Why is modulus different in different programming languages?

查看:79
本文介绍了为什么模数在不同的编程语言中有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Perl

print 2 % -18;

->

-16

Tcl

puts [expr {2 % -18}]

->

-16

但是VBScript

but VBScript

wscript.echo 2 mod -18

->

2

为什么有区别?

推荐答案

维基百科答案是这里很有帮助.

一个简短的总结是,可以将任何整数定义为

A short summary is that any integer can be defined as

a = qn + r

a = qn + r

所有这些字母都是整数,并且

where all of these letters are integers, and

0< = | r | < | n |.

0 <= |r| < |n|.

几乎每种编程语言都要求(a/n)* n +(a%n)= a.因此,模数的定义几乎总是取决于整数除法的定义.用负数2/-18 = 0或2/-18 = -1进行整数除法有两种选择.通常,取决于%运算符取决于您的语言中的哪一种.

Almost every programming language will require that (a/n) * n + (a%n) = a. So the definition of modulus will nearly always depend on the definition of integer division. There are two choices for integer division by negative numbers 2/-18 = 0 or 2/-18 = -1. Depending on which one is true for your language will usually change the % operator.

这是因为2 =(-1)* -18 +(-16)和2 = 0 * -18 +2.

This is because 2 = (-1) * -18 + (-16) and 2 = 0 * -18 + 2.

对于Perl而言,情况很复杂. 手册页说:请注意,在范围内使用整数时,% 使您可以直接访问由C编译器实现的模运算符.对于负操作数,此运算符的定义不是很好,但是执行速度更快."因此,如果使用integer是,则可以为Perl选择任一选项(如C)在适用范围.如果使用整数不在范围内,则手册将说明:如果$ b为负数,则$ a%$ b为$ a减去$ b的最小倍数,该倍数不少于$ a(即结果将小于或等于等于零)."

For Perl the situation is complicated. The manual page says: "Note that when use integer is in scope, "%" gives you direct access to the modulus operator as implemented by your C compiler. This operator is not as well defined for negative operands, but it will execute faster. " So it can choose either option for Perl (like C) if use integer is in scope. If use integer is not in scope, the manual says " If $b is negative, then $a % $b is $a minus the smallest multiple of $b that is not less than $a (i.e. the result will be less than or equal to zero). "

这篇关于为什么模数在不同的编程语言中有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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