2015-09-26 128 views
0

爲什麼會有顯示的精度損失的錯誤雖然hackerrank答案是隻能爲整數?當我使用雙倍它打印出像2.0,5.0這是不匹配的輸出爲什麼Math.pow()顯示精度下降?

public class Solution { 

    public static void main(String args[]) throws IOException { 
     /* enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ 
     Scanner s = new Scanner(System.in); 
     int t = s.nextInt(); 
     int x, y; 
     int p = 2; 
     int q = 0; 
     int i, j; 
     for(j = 0; j < t; j++){ 
      y = 0; 
      x = 0; 
      int a = s.nextInt(); 
      int b = s.nextInt(); 
      int n = s.nextInt(); 
      x = (a + Math.pow(p, q) * b); 
      System.out.print(x); 

      for(i = 1; i < n; i++) { 
       y = (x + Math.pow(p, i) * b); 
       System.out.print(y); 
       x = y; 
      } 
      System.out.println(); 
     } 
    } 
} 
+0

提示的第二個電話:什麼是'Math.pow()'返回類型? – RealSkeptic

+1

我已經將代碼格式化爲可讀性,因爲發佈的代碼格式很差。將來我強烈建議你自己做。格式化是非常重要的,因爲如果你的代碼不是可接受的標準格式,它的可讀性不好,如果它不可讀,這是不可理解的,這可能會減少你獲得及時正面答案的可能性。 –

+0

'Math.pow'的返回類型是double,您將其分配給一個int變量'x'。 –

回答

0

當你」請確保pi始終是整數,您可以調用Integer的Math.pow(...)調用。鑄造特殊照顧加(int)的號召:

(a + ((int)Math.pow(p, q)) * b);

同樣爲Math.pow(...)