public class 一元三次方程 { publicstaticvoidmain(String[] args) { double a, b, c, d; // ax^3 + bx^2 + cx + d = 0 Scannerscanner=newScanner(System.in); // 输入系数 // System.out.println("请输入方程的系数(空格分隔):"); a = scanner.nextDouble(); b = scanner.nextDouble(); c = scanner.nextDouble(); d = scanner.nextDouble();
double i, temp; double[] num = newdouble[3]; // 存放实根 intk=0; // 记录实根数目
for (i = -100; i <= 100; i += 0.01) { temp = a * Math.pow(i, 3) + b * Math.pow(i, 2) + c * i + d; if (temp > -0.01 && temp < 0.01) num[k++] = i; if (k == 3) break; } // 输出实根 System.out.printf("%.2f %.2f %.2f", num[0], num[1], num[2]); } }