方法返回类型忽略

Ben*_*eno 0 java

我试图得到这个方法,我把x*y的值作为long返回.但是,它返回一个int.据我所知,在方法头中指定返回long是需要做什么的?

我无法得到所需的结果,我错过了什么?

public class Returnpower 
{

    public long power(int x,int n) 
    {   
        int total = x * n;
        if(x < 0 && n < 0)
        {
            System.out.println("X and/or N are not positive");
            System.exit(0);
        }
        return (total);

    }

    public static void main(String[] args)
    {
        Returnpower power = new Returnpower();

        System.out.println(power.power(99999999,999999999));
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

469325057
Run Code Online (Sandbox Code Playgroud)

谢谢

Jon*_*eet 6

不,它正在回归long.这只是你在执行运算的32位整数运算第一.看看你是如何做算术的:

int total = x * n;
Run Code Online (Sandbox Code Playgroud)

你甚至没有结果存储long,所以我看不出你如何期望它保留一个完整的long值.你需要total成为一个long- 并且你必须制作一个操作数a long才能使乘法发生在64位.

要强制在64位算术中进行乘法,您应该转换其中一个操作数:

long total = x * (long) n;
Run Code Online (Sandbox Code Playgroud)

或者,只是total完全摆脱变量 - 我建议使用参数之前执行参数验证:

public long power(int x, int n) 
{   
    if (x < 0 && n < 0)
    {
        // Use exceptions to report errors, not System.exit
        throw new IllegalArgumentException("x and/or n are negative");
    }
    return x * (long) n;
}
Run Code Online (Sandbox Code Playgroud)

(此外,这显然不是以与Math.pow例如...... 相同的方式执行动力操作)