前几天在牛客上看到一个面试题:,给定x,求y
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 import java.util.Scanner;public class 解指数方程 { private static double accuracy = 1e-8 ; public static void main (String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { double x = sc.nextDouble(); double y = solve(x); System.out.printf("x = %f, y = %f\n" , x, y); } } public static double solve (double x) { if (x == 0 ) { return 0 ; } boolean flag = x > 0 ; x = Math.abs(x); double left = 0 , right = x; double mid = 0 ; while (left < right) { mid = (right - left) / 2 + left; double diff = calculate(mid) - x; if (Math.abs(diff) <= accuracy) { if (!flag) { mid *= -1 ; } break ; } else if (diff > 0 ) { right = mid; } else { left = mid; } } return mid; } private static double calculate (double num) { return Math.pow(num, 7 ) + 0.5 * num; } }
测试运行结果:1 2 3 4 5 6 7 8 9 10 11 12 13 14 -100 x = -100.000000 , y = -1.928028 1 x = 1.000000 , y = 0.916197 0 x = 0.000000 , y = 0.000000 100 x = 100.000000 , y = 1.928028 38291 x = 38291.000000 , y = 4.515693 37261.77321 x = 37261.773210 , y = 4.498150 32918429 x = 32918429.000000 , y = 11.855500