gpt4 book ai didi

java - Java 的 % 运算符会溢出吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:45:34 25 4
gpt4 key购买 nike

在 C 和 C++ 中,根据 Shafik's postINT_MIN % -1 的行为似乎未定义/平台相关.

在 Java 中,% 运算符会溢出吗?

考虑这段代码:

public class Test {
public static void main(String[] args) {
// setup variables:
byte b = Byte.MIN_VALUE % (-1);
short s = Short.MIN_VALUE % (-1);
int i = Integer.MIN_VALUE % (-1);
long l = Long.MIN_VALUE % (-1);

// my machine prints "0" for all:
System.out.println(b);
System.out.println(s);
System.out.println(i);
System.out.println(l);
}
}

是否有独立于平台的保证上述结果为0

最佳答案

JLS section 15.17.3它说:

In C and C++, the remainder operator accepts only integral operands, but in the Java programming language, it also accepts floating-point operands.

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0). It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive;

关于java - Java 的 % 运算符会溢出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25765232/

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