铸造的乘法两个正整数结果长是负值负值、乘法、两个、结果

2023-09-08 09:11:40 作者:爱海、搁浅

我有code是这样的:

  INT A = 629339;
INT B = 4096;
长解析度= A * B;
 

结果是 -1717194752 但如果我加一个手动施放长长RES =((长)一)* B; 长RES =(长)A * B ; 的结果是正确的 2577772544 谁可以解释它是如何工作的。

解决方案

 长解析度= A * B;
 

A * B 除非你在末尾加上L将被视为整数(或)铸造。

根据 Java教程

  

int数据类型是一个32位有符号二进制补码整数。它有2,147,483,648最小值和2147483647的最大值(含)。对于整数值,此数据类型通常是默认选项,除非是有原因(如上述)选择别的东西。

正整数加减乘除四则混合运算求值方法 java

I have code like this :

int a = 629339;
int b = 4096;
long res = a*b;

The result is -1717194752 but if I add one manual cast to long long res = ((long)a)*b; or long res = (long) a*b; the result is correct 2577772544 Who can explain how does it works.

解决方案

long res = a*b;

a*b will be treated as integer unless you add 'l' at end (or) cast.

As per java tutorial

The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else.