You are to design and implement a C++ program that will solve for the roots of a
ID: 3673466 • Letter: Y
Question
You are to design and implement a C++ program that will solve for the roots of a quadratic equation of the form below:
ax2 + bx + c = 0
Input: Read in a, b, c using input entered from a text file. Use a trailer of
0 0 0 at the end of the data file.
Calculations:
d = b*b - 4ac (d=discriminant)
If the result < 0, there are no real roots to the equation
If the result = 0, there is one real root (-b/2a)
If the result > 0, there are two real roots to the equation
Root1 = -b - sqrt( b2 - 4ac)/2a
Root2 = -b + sqrt( b2 - 4ac)/2a
Exception: Do not solve for roots if a = 0 – code as an error message
Output: Print a, b, c, the two roots, and/or any errors messages. Allow the user to continue executing the program until out of data using a trailer on the input data file (use a while loop like while (a != 999)) or continue until user says to stop (use a do-while loop until response is not “Yes”).
The output should look like this:
A B C Root 1 Root 2
6 -10 -4 ? ?
2 6 9 ? ?
. . . . .
. . . . .
Run the program with the following set of data:
6 -10 -4
2 6 9
2 4 8
0 2 4
2 4 2
Explanation / Answer
#include<iostream.h>
#include<conio.h>
#include<math.h>
using namespace std;
int main()
{
float a,b,c,d;
//initializing
float Root1,Root2;
//initializing with root1,root2
cout<<“ax^2+bx+c”;
//given equation
cout<<“Enter the coefficients”;
cin>>a>>b>>c>>d;
d=b*b-4*a*c;
//for result
//here d is the result
if(d==0)
{
root1=(-b)/2*a;
root2=root1;
cout<<“there is only one root”;
}
else if(d<0)
{
root1=(-b)/2*a;
root2=sqrt(-d)/2*a);
cout<<“there are no real roots to the equation”;
}
else if(d>0)
{
root1=-b-sqrt(b2-4ac)/2a;
root2=-b+sqrt(b2-4ac)/2a;
cout<<“there are two real roots to the equation;
}
else
{
cout<<“default”;
}
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.