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

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

问题描述

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 编译器实现的模运算符.对于负操作数,此运算符没有很好地定义,但它会执行得更快.因此,如果使用整数,它可以为 Perl(如 C)选择任一选项在适用范围.如果 use integer 不在范围内,手册说如果 $b 是负数,则 $a % $b 是 $a 减去不小于 $a 的 $b 的最小倍数(即结果将小于或等于零)."

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天全站免登陆