簡體   English   中英

為什么Math.pow()顯示精度損失?

[英]Why is Math.pow() showing loss of precision?

為什么在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();
        }
    }
}

當您確定pi始終是整數時,可以將Math.pow(...)調用轉換為Integer。 您通過在呼叫中添加(int)進行投射:

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

Math.pow(...)的第二次調用也是如此

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM