计算功率的输出错误



我有下面的代码。

import java.util.ArrayList;
import java.math.*;
import java.util.Arrays;
import java.util.Collections;
public class Dummy {
    public static void main(String args[]) throws Exception {

    int n=12;
    double val=(3+Math.sqrt(5));
    double ne=Math.pow(val, n);
    String new2=String.valueOf(ne);
    System.out.println(ne);
    String[] new1=new2.split("\.");
    if(new1[0].length()>3){
        new1[0]=new1[0].substring(Math.max(new1[0].length() - 4, 0));
         if(new1[0].length()<3){
                new1[0]=("0").concat(new1[0]);
            }
         else{
             new1[0]=new1[0];
         }
    }
    else if(new1[0].length()<2){
        new1[0]=("00").concat(new1[0]);
    }
    else if(new1[0].length()<1){
        new1[0]=("000").concat(new1[0]);
    }

    else if(new1[0].length()<3){
        new1[0]=("0").concat(new1[0]);
    }
    System.out.println(new1[0]);
    }
}

在这里,我试图计算sum of 3 with root 5 and whole to power of 12

(3+sqrt(5))^12

当我这样做时,我得到的结果是4.246814719604947E8但实际上答案是424681471.960494。 请让我知道我哪里出错了。

这是科学记数法。

如果您不希望它采用此表示法,可以尝试

public static void main(String[] args) {
    Double d = Math.pow(3+Math.sqrt(5),12);
    System.out.println(d); //4.246814719604947E8
    System.out.println(new BigDecimal(d).toPlainString()); //424681471.960494697093963623046875
}

使用这个System.out.println(String.format("%f", ne));

你注意到答案中的E8了吗?那么答案是正确的:)

你得到的答案是正确的。

4.246814719604947E8

表示 4.246814719604947 乘以 10^8。如果将小数点向右移动 8 位,您会看到预期的答案。

最新更新