Java黑皮书课后题第3章:*3.1(代数:解一元二次方程)可以使用下面的公式求一元二次方程ax2+bx+c=0,编写程序提示用户输入a b c的值,并显示基于判断式的结果
import java.util.Scanner;
public class Q3_1 {
private static void r1AndR2(double a,double b,double c){
if (b*b-4*a*c<0){
System.out.println("The equation has no real roots");
}
else if (b*b-4*a*c == 0){
double r1 = (-b+Math.pow((b*b-4*a*c),0.5))/2*a;
System.out.println("The equation has one root " + r1);
}else {
double r2 = (-b-Math.pow((b*b-4*a*c),0.5))/2*a;
double r1 = (-b+Math.pow((b*b-4*a*c),0.5))/2*a;
System.out.printf("The equation has two roots %.6f",r1);
System.out.printf("and %.6f",r2);
}
}
public static void main(String[] args) {
System.out.print("Enter a, b, c: ");
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
r1AndR2(a,b,c);
}
}