java 整数相乘为负,使用正数在Java中以乘法给出负值的整数

public class Test {

public static void main(String[] args) {

int sum=0;

for(int i=1;i<10;i++)

sum = sum+i*i*i*i*i*i*i*i*i*i;

System.out.println(sum);

}

}

OUTPUT:619374629

for(int i=1;i<10;i++)

sum = sum+i*i*i*i*i*i*i*i*i*i*i;

System.out.println(sum);

OUTPUT:

-585353335

In the second output i thought the integer range crossed.But why it is giving -ve number.It need to give me an error.What is the reason for this behaviour?

Thanks in advance...

解决方案

You have overflowed the size of a 32 bit integer.

Consider what happens when i is equal to 10:

sum = sum + 100000000000 //1 with 11 zeroes

But the maximum positive number that can be stored in a 32 bit integer is only about 2 billion (2 with nine zeroes).

In fact, it gets even worse! The intermediate calculations will be performed with limited precision, and as soon as the multiplication of 10*10*10*10... overflows, then the 10s will be being multiplied with a weird negative number, and be already wrong.

So the number you end up with is not seeming to follow any rules of arithmetic, but in fact it makes perfect sense once you know that primitive integers have limited storage.

The solution is to use 64-bit long and hope you don't overflow THAT too, if you do then you need BigInteger.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值