Could anyone help me with the following project? (The language is C++) Instructi
ID: 3675829 • Letter: C
Question
Could anyone help me with the following project? (The language is C++)
Instructions:
You are to design and implement a 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
add four more data lines including tests for a=0, d<0, d=0, d>0.
Explanation / Answer
#include<iostream.h>
#include<fstream.h>
#include<math.h>
void main()
{
int a[5],b[5],c[5],i=0,d,r1[5],r2[5];
ifstream read("file.txt");
while(i<5)
{
read>>a[i]>>b[i]<<c[i];
i++;
}
for(i=0;i<5;i++)
{
d=b[i]*b[i]-4*a[i]*c[i];
if(d<0)
{
cout<<"No real Roots";
r1[i]=0;
r2[i]=0;
}
else if(d==0)
{
r1[i]=-b[i]/(2*a[i]);
r2[i]=0;
}
else if(d>0)
{
r1[i]=(-b[i]-sqrt(b[i]*b[i] - 4*a[i]*c[i]))/(2*a[i]);
r2[i]=(-b[i]-sqrt(b[i]*b[i] + 4*a[i]*c[i]))/(2*a[i]);
}
}
for(i=0;i<5;i++)
{
cout<<a[i]<<" "<<b[i]<<" "<<c[i]<<" "<<r1[i]<<" "<<r2[i]<<endl;
}
getch();
}