Question: Write a program in C++ to solve for the complex roots of the quadratic equation az^2 + bz + c =0, with solution: z =
Write a program in C++ to solve for the complex roots of the quadratic equation az^2 + bz + c =0, with solution: z = (-bsqrt(b^2-4ac))/ 2a Either come up with your own algorithm, or follow the following one:
Input: 1. Define floats a, b, and c and read their values from the console with appropriate prompts (see examples below).
Calculation: 2. Define a boolean variable, i.e., complex, and initialize it to false. This will indicate if the result has an imaginary part.
3. Define two variables, x and y, that will hold the terms x=-b/(2a) and y=sqrt(radicand)/(2a). Initialize them to zero.
4. If a is not zero (otherwise, cannot apply the solution) do the following:
a. Define a variable called for example radicand and set it to the term inside the radical, i.e., b^2-4ac
b. If radicand is negative, set complex to true and make radicand positive, i.e., set radicand to -radicand.
c. compute x =b/(2a) and y =radicand/(2a)
5. Else, if b is not zero then set x =-c/b (if a is 0 but b is not, the equation is linear, i,e, bz + c =0, with one real solution)
Output:
6. If a is not zero or b is not zero (which means that there is a solution) do the following:
a. If y is not zero (which means that there there are two solutions) do the following:
i. If complex is true, print x + i |y| and x - i |y|, following the examples.
Note that | | means absolute value (use math function fabsf).
Also, note that + i and - i are printed as strings, but not the x and |y|.
ii. Else, (not complex) print x + y and x - y (see output examples)
b. Else (one solution), print just x (because y is zero) (see output examples)
7. Else, print error message such as Cannot solve for z. This is because the if a and b are zero, then the equation reduces to c = 0, which does not depend on z.
The output should look similar to the following examples: Enter the coefficients of a z^2 + b z + c = 0 a = 2 b = -2 c = -12 Solutions: z = 3 z = -2 Enter the coefficients of a z^2 + b z + c = 0 a = 1 b = 2 c = 3 Solutions: z = -1 + i 1.41421 z = -1 - i 1.41421 Enter the coefficients of a z^2 + b z + c = 0 a = 0 b = 3 c = -36 Solution: z = 12 Enter the coefficients of a z^2 + b z + c = 0 a = 0 b = 0 c = 5
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
