为什么Math.pow()显示精度损失?

时间:2015-09-26 20:57:37

标签: java loops

为什么有一个错误显示精度损失,虽然hackerrank中的答案只是整数?当我使用double时,它打印出像2.0,5.0那样与输出不匹配

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

1 个答案:

答案 0 :(得分:0)

如果您确定pi始终是整数,则可以将Math.pow(...)调用转换为Integer。通过在呼叫中添加(int)来进行投射:

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

Math.pow(...)

的第二次调用也是如此