2015-09-26 30 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(...)