第三章第一题(代数:解一元二次方程)(Algebra: solve quadratic equations)

*3.1(代数:解一元二次方程)可以使用下面的公式求一元二次方程\LARGE ax^{2}+bx+c = 0 两个根:

\LARGE r_{1} =\tfrac{ -b+\sqrt{b^{2}-4ac}}{2a}    和   \LARGE r_{2} =\tfrac{ -b-\sqrt{b^{2}-4ac}}{2a}  

\LARGE b^{2}-4ac称作一元二次方程的判别式。如果它是正值,那么一元二次方程就有两个实数根。如果它为0,方程式就只有一个根。如果它是负值,方程式无实数根。

编写程序,提示用户输入a、b和c的值,并且显示基于判别式的结果。如果这个判别式为正,显示两个根。如果判别式为0,显示一个根。否则,显示“The equation has no real roots”(该方程式无实数根)。

注意,可以使用Math.pow(x,0.5) 来计算\LARGE \sqrt{x}

下面是一些运行示例:

Enter a, b, c:1.0 3 1

The equation has two roots -0.381966 and -2.61803

Enter a, b, c:1 2.0 1

The equation has one root -1.0

Enter a, b, c:1 2 3

The equation has no real roots

 

*3.1(Algebra: solve quadratic equations) The two roots of a quadratic equation \LARGE ax^{2}+bx+c = 0 can be obtained using the following formula:

\LARGE r_{1} =\tfrac{ -b+\sqrt{b^{2}-4ac}}{2a}    and   \LARGE r_{2} =\tfrac{ -b-\sqrt{b^{2}-4ac}}{2a}

\LARGE b^{2}-4ac is called the discriminant of the quadratic equation. If it is positive, the equation has two real roots. If it is zero, the equation has one root. If it is negative, the equation has no real roots.

Note you can use Math.pow(x, 0.5) to compute \LARGE \sqrt{x}.

Here are some simple runs:

Enter a, b, c:1.0 3 1

The equation has two roots -0.381966 and -2.61803

Enter a, b, c:1 2.0 1

The equation has one root -1.0

Enter a, b, c:1 2 3

The equation has no real roots

 

下面是参考答案代码:

import java.util.*;

public class SolveQuadraticEquationsQuestion1 {
	public static void main(String[] args) {
		double a, b, c, discriminant, r1, r2;
		System.out.print("Enter a, b, c:");
		Scanner input = new Scanner(System.in);
		a = input.nextDouble();
		b = input.nextDouble();
		c = input.nextDouble();
		
		discriminant = Math.pow(b, 2) - 4 * a * c;
		
		if(discriminant > 0)
                {
			r1 = (-1 * b + Math.pow(discriminant,0.5)) / (2 * a);
			r2 = (-1 * b - Math.pow(discriminant,0.5)) / (2 * a);
			System.out.println("The equation has two roots " + r1 
								+ " and " + r2);
		}
		else if(discriminant == 0)
                {
			r1 = (-1 * b) / (2 * a);
			System.out.println("The equation has one root " + r1);
		}
		else
                {
		    System.out.println("The equation has no real roots");
		}
		input.close();
	}
}

运行效果:

 

注:编写程序要养成良好习惯
如:1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)