[英]Why do the modulo operation result take the dividend's type instead of the divisor's type?
Why the result of the modulo operation a % b
has the same type than a
instead of the b
type?为什么模操作的结果
a % b
具有相同类型比a
,而不是b
型?
The remainder after a division never is going to be higher than the divisor, so the type of the result will fit in the divisor's type.除法后的余数永远不会高于除数,因此结果的类型将适合除数的类型。 So in
a % b
, the result is going to fit in the b
's type.所以在
a % b
,结果将适合b
的类型。
So if b
is an Int
, the result should be Int
as well.所以如果
b
是一个Int
,结果也应该是Int
。 Why is it a Long
?为什么是
Long
?
Example:例子:
val a: Long = Long.MaxValue
val b: Int = 10
a % b
Result:结果:
a: Long = 9223372036854775807
b: Int = 10
res0: Long = 7
In the res0
, I was expecting an Int
.在
res0
,我期待一个Int
。
I asked the same in the Scala contributors forum to be able to follow a conversation.我在Scala 贡献者论坛上问了同样的问题,以便能够关注对话。
As mentioned in comments, Scala follows Java here.正如评论中提到的,Scala 在这里遵循 Java。 And Java follows C. And C actually has a good reason for this!
Java 紧随 C 之后。而 C 实际上有一个很好的理由! Namely:
即:
it has separate signed and unsigned types;它有单独的有符号和无符号类型;
result of a % b
has the same sign as a
(eg -10 % 3
is -1
).的结果
a % b
具有相同的符号作为a
(例如-10 % 3
是-1
)。 (This wasn't required in older C versions, but always allowed.) (这在旧的 C 版本中不是必需的,但总是允许的。)
So if -10
above is signed long
and 3
is unsigned int
, then the result can't be the same type as the divisor because it must be signed.因此,如果上面的
-10
是有signed long
并且3
是unsigned int
,则结果不能与除数的类型相同,因为它必须是有符号的。 It couldn't be signed int
either, because instead of 3
we could have something which fits into unsigned int
but not signed int
.它也不能是
signed int
,因为我们可以有一些适合unsigned int
但不适合signed int
东西,而不是3
。 Applying the same rules as for other arithmetical operators gives reasonable return type, so that's what C does.应用与其他算术运算符相同的规则给出合理的返回类型,这就是 C 所做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.