“%”后面的模数默认变量类型是什么。
variable1 = variable2 % variable3;
这意味着,java是否有可能将variable3的类型从long更改为int?
最佳答案
简短回答 - 不,不会 - 它会告诉您发生了精度损失!因为 Java 是一种强类型语言(如果需要,我愿意对此进行更正),所以您需要显式维护左值和右值的类型。使用如下:
(这些不是代码行 - 只是解释)
int res = int var1 % int var2; // res as modulo of var1 and var2 (all int, no loss)
long res = int var1 % int var2; /* res as modulo of var1 and var2 (res size is bigger,
* no loss) */
long res = long var1 % int var2; /* res as module of var1 and var2 (the divider is
* smaller size than dividend and quotient, so no
* problem */
其他任何事情都会失去精度。另外,使用模 % 符号时的左值 rvlaue 排列很重要。
long
只是将范围从 32 位扩展到 64 位。这就是为什么当您混合它们而不平衡左值和右值(相对于“=”运算符和%运算符)时,编译器会遵守。对于您的情况,除非您正在执行特定的按位运算,否则不要使用 long
不必要的。我建议尽可能使用 Shorts(如果您需要 32 位那么大的东西,则使用 int
)。
关于java - 模取什么变量类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26819397/