在Java中使用正数乘法给出负值的整数 [英] integer giving negative values in java in multiplication using positive numbers

查看:224
本文介绍了在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

在第二个输出中,我认为整数范围已经过了,但是为什么要给出-ve数字呢?它需要给我一个错误.此行为的原因是什么?

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?

预先感谢...

推荐答案

您溢出了32位整数的大小.

You have overflowed the size of a 32 bit integer.

考虑当我等于10时会发生什么:

Consider what happens when i is equal to 10:

sum = sum + 100000000000 //1 with 11 zeroes

但是可以存储在32位整数中的最大正数只有大约20亿(2个带有9个零).

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

实际上,情况甚至更糟!中间计算将以有限的精度执行,并且一旦10 * 10 * 10 * 10 ...的乘法溢出,那么10s将与一个怪异的负数相乘,并且已经是错误的了.

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.

解决方案是使用64位的long,希望您也不要溢出,如果需要,则需要BigInteger.

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

这篇关于在Java中使用正数乘法给出负值的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆