Solving 2nd degree equations (JAVA) • boolean real-sols(double a, double b, doub
ID: 3826964 • Letter: S
Question
Solving 2nd degree equations (JAVA)
• boolean real-sols(double a, double b, double c): it returns true if the 2nd degree equation ax2 + bx + c has real solutions
• double solution1(double a, double b, double c): If the equation ax2 + bx + c has real solutions it return the smallest of the two. If it doesn’t have real solutions it should return the value 0 and an error message.
• double solution2(double a, double b, double c): If the equation ax2 + bx + c has real solutions it return the biggest of the two. If it doesn’t have real solutions it should return the value 0 and an error message.
• Test your methods within a class and check that they work properly. Use the method real-sols(double a, double b, double c) in the implementation of the other 2 methods.
Explanation / Answer
Quadratic.java
public class Quadratic {
public boolean realSol(double a, double b, double c)
{
return b*b -4*a*c >= 0;
}
double solution1(double a, double b, double c)
{
double sol = 0;
if(realSol(a, b, c))
{
double sol1 = (-b + Math.sqrt(b*b -4*a*c))/2*a;
double sol2 = (-b - Math.sqrt(b*b -4*a*c))/2*a;
sol = sol1 < sol2 ? sol1 : sol2;
}
else
{
System.out.println("No real roots");
}
return sol;
}
double solution2(double a, double b, double c)
{
double sol = 0;
if(realSol(a, b, c))
{
double sol1 = (-b + Math.sqrt(b*b -4*a*c))/2*a;
double sol2 = (-b - Math.sqrt(b*b -4*a*c))/2*a;
sol = sol1 > sol2 ? sol1 : sol2;
}
else
{
System.out.println("No real roots");
}
return sol;
}
public static void main(String[] args)
{
double a, b, c;
Quadratic q = new Quadratic();
a = 1; b = 2; c = 1;
System.out.println("Solution of : 1x^2 + 2x + 1, x1 = " +
q.solution1( a, b, c) + " x2 = " +
q.solution2(a, b, c));
a = 1; b = 1; c = 1;
System.out.println("Solution of : 1x^2 + x + 1");
System.out.println("x1 = " +
q.solution1( a, b, c) + " x2 = " +
q.solution2(a, b, c));
}
}
Sample run:
Solution of : 1x^2 + 2x + 1, x1 = -1.0 x2 = -1.0
Solution of : 1x^2 + x + 1
No real roots
No real roots
x1 = 0.0 x2 = 0.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.