简体   繁体   中英

Java Math type casting

So I have the following program:

import java.lang.Math;

public class Test{
    public static void main(String[] args) {
        int value = (int)Math.pow(11,11);
        System.out.println(value);
    }
}

I want to print the integer value of 11 to the power of 11. I know that Math.pow(11,11) would return a double 2.85311670611E11 which is correct. But when I type cast it to int I would get 2147483647 which is clearly not correct.

So why does this happen? And how can I fix it?

Thanks

You have to use Long for this case.

int, as a signed integer, can be only a number with max 2^32 if it is unsigned, or 32 digits number, in other words its limit is from 0 to 2,147,483,647, and it is giving you just the limit.

Try using Long object, that is 2^64 and will give you the correct answer.

这是int类型的上限,您可以使用long代替,也可以在java.math.BigInteger尝试BigInteger ,它永远不会溢出。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM