编程题:18
import java.util.Scanner;

public class Main {
// 计算多项式在 x 处的值
public static double polynomial(double a3, double a2, double a1, double a0, double x) {
return a3 * x * x * x + a2 * x * x + a1 * x + a0;
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    // 读取多项式系数
    double a3 = scanner.nextDouble();
    double a2 = scanner.nextDouble();
    double a1 = scanner.nextDouble();
    double a0 = scanner.nextDouble();
    // 读取区间端点
    double a = scanner.nextDouble();
    double b = scanner.nextDouble();

    // 二分法求根
    while (b - a > 1e-4) {  // 控制精度,确保结果精确到小数点后 2 位
        double mid = (a + b) / 2;
        double fMid = polynomial(a3, a2, a1, a0, mid);
        double fA = polynomial(a3, a2, a1, a0, a);

        if (fMid * fA < 0) {
            b = mid;
        } else {
            a = mid;
        }
    }

    // 输出结果,精确到小数点后 2 位
    System.out.printf("%.2f\n", (a + b) / 2);
}

}

posted on 2025-05-12 23:22  Swishy  阅读(4)  评论(0)    收藏  举报