14.1k views
0 votes
Write pseudocode for an algorithm for finding real roots of equation ax2 + bx + c = 0 for arbitrary real coefficients a, b, and

c. (you may assume the availability of the square root function sqrt (x).)

1 Answer

5 votes

To find the roots of a quadratic equation
ax^2+bx+c=0 you need to use the quadratic formula


x_(1,2) = (-b\pm√(b^2-4ac))/(2a)

This implies that if
b^2-4ac<0 the equation has no solutions, if
b^2-4ac=0 the equation has one double solution, and two distinct solutions otherwise.

So, the pseudocode could be something like this:

double delta = b*b - 4*a*c;

if (delta < 0) print ("There are no real solutions!");

else if(delta = 0) {

double x = -b/(2*a);

print("There is a double solution: " + x);

} else {

double det = sqrt(delta);

double x1 = (-b+det)/(2*a);

double x1 = (-b-det)/(2*a);

print ("The two solutions are " + x1 + "and" + x2);

}

User Vincent Pazeller
by
6.2k points