2013-08-16 71 views
0

我想讓這個方法返回x * y的值作爲long。但是,它返回一個int。據我所知在方法頭中指定要返回一個長是需要做什麼?方法返回類型被忽略

我無法得到所需的結果,我錯過了什麼?

代碼

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)); 
    } 
} 

輸出

469325057 

感謝

+0

'int' *'int' ='int',你需要至少對其中一人進行演員陣容,然後應用該操作。 –

+0

那麼你使用int作爲參數,並在函數中 –

+0

我試了long total = x * n;這給了我相同的結果,但總長= x *(long)n;爲什麼這是爲什麼? – BenniMcBeno

回答

6

不,它返回一個long。這只是你首先在32位整數算術中執行算術。看看你是如何做算術:

int total = x * n; 

你甚至不存儲結果作爲long,所以我不知道你怎麼能指望它保留一個完整的long值。您需要totallong - 您必須將其中一個操作數設置爲long才能使乘法運算髮生在64位中。

要強制乘法64位運算的發生,你應該投一個操作數:

long total = x * (long) n; 

或者,只是完全擺脫了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; 
} 

(另外,這顯然不是執行功率運算關合作以同樣的方式作爲Math.pow,例如...)

+0

不是更容易改變PARAMS很長?總變量 –

+0

@LoïcFaure-Lacroix:可能,但這可能不是一種選擇。 (例如,它可能是在實際代碼中實現一個接口。)還要注意,在'long'算術中乘以兩個'int'大小的值不會溢出,這可能是一個很好的屬性以知道... –

+0

對啊,對於接口是有意義的,並且它確保我們不能有一個大於長的'x * y'。 –

1

變化intlong

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

出把

99999998900000001