解一元二次方程:
可以使用下面的公式求元二次方程ax*x+bx+c=0的两个根:
b*b- 4ac称作一元二次方程的判别式。如果它是正值,那么一元二次方程就有两个实数根。如果它为0,方程式就只有一个根。如果它是负值,方程式无实数根。
编写程序,提示用户输入a、b和c的值,并且显示基于判别式的结果。如果这个判别式为正,显示两个根。如果判别式为0,显示一个根。否则,显示“Theequation has no real roots" (该方程式无实数根)。
注意,可以使用Math.pow(x , 0.5)或Math.sqrt( x )来计算的值。下面是一些运行示例。
Enter a, b, c:1.0 3 1 8
The equation hastwo roots -0.381966 and -2.61803
Enter a, b, c:1 2.0 1 8
The equation hasone root -1.0
Enter a, b, c: 1 2 3 8
The equation hasno real roots
代码如下:
import java.util.Scanner;
public class fangcheng {
public static void main(String[] args) {
//输入a,b,c值
System.out.println("请分别输入a,b,c的值");
Scanner input=new Scanner(System.in);
double a=input.nextDouble();
double b= input.nextDouble();
double c= input.nextDouble();
input.close();
//求det和根
double det=b*b-4*a*c;
double R1=(-b+Math.sqrt(det))*1.0/2.0*a;
double R2=(-b-Math.sqrt(det))*1.0/2.0*a;
//输出
if(det<0){
System.out.println("THeequation has no roots");
}
if(det>0){
System.out.println("The equation has two roots");
System.out.println("R1="+R1);
System.out.println("R2="+R2);
}
if(det==0){
System.out.println("The equation has one root");
System.out.println("R="+R1);
}
}