Java promotes the exact value of N from n to n

I have this simple question

Sample input:

Enter a 95.123

Enter two 12

Raising the first input to the second input must give an accurate power value Like this: 548815620517731830194541.8990253434157159735359672218698

I can't make it.

This is what I have done so far I think I missed something

System.out.println("Input One");
Scanner scanner = new Scanner(system.in);
Double inputOne = scanner.nextDouble();
System.out.println("Input Two");
Double inputTwo = scanner.nextDouble();
Double result = Math.pow(inputOne,inputTwo);
BigDecimal big = new BigDecimal(result);
System.out.println(big);

What did I miss?

Solution

You use double to start, and double doesn't fully represent 95.123 Then, you will use math. With a double value Pow, which will further reduce the accuracy It makes no sense to convert an already corrupted value to a high-precision value... It can't magically recover the data

Just pass the string to the BigDecimal constructor of the first parameter, and then POW is passed to the calculation

Example code:

import java.math.BigDecimal;

public class Test {

    public static void main(String[] args) {
        BigDecimal inputOne = new BigDecimal("95.123");
        int power = 12;
        BigDecimal result = inputOne.pow(power);
        System.out.println(result);
    }
}

Output:

548815620517731830194541.899025343415715973535967221869852721

(it seems that your expected value is actually truncated... The exact value should end with 1, because 312 ends with 1.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>