A quadratic equation ax 2 + bx + c = 0 has three inputs (a,b,c) and two outputs
ID: 3642615 • Letter: A
Question
A quadratic equation ax2
+ bx + c = 0 has three inputs (a,b,c) and two outputs (x1 and
x2). We assume that x1 = r1 + i*t1 and x2 = r2 + i*t2, i=sqrt(-1).
Write an engine program for solving the quadratic equation that accepts inputs (a.b.c)
as command line arguments.
If there are three command line arguments, the program should display the results (x1
and x2) on the screen.
If there are no command line arguments then the engine should prompt the user to
enter a,b,c and then compute and display the results (x1 and x2) on the screen.
If there are 4 command line arguments (a b c filename.dat) then the engine should
take a,b,c and store the resulting x1 and x2 in filename.dat working in silent mode (no
use of screen). Write a master program that activates the engine using system(
Explanation / Answer
#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<math.h>
using namespace std;
int main(int argc,char* argv[])
{
float a,b,c;
float r1,t1,r2,t2;
if(argc>=4)
{
a = atof(argv[1]);
b = atof(argv[2]);
c = atof(argv[3]);
float disc = b*b - 4*a*c;
if(disc>0)
{
t1 = t2 = 0;
r1 = (-b+sqrt(disc))/(2*a);
r2 = (-b-sqrt(disc))/(2*a);
}
else if(disc==0)
{
t1 = t2 = 0;
r1 = (-b)/(2*a);
r2 = (-b)/(2*a);
}
else
{
r1 = r2 = (-b)/(2*a);
t1 = sqrt(-disc)/(2*a);
t2 = -sqrt(-disc)/(2*a);
}
if(argc==5)
{
ofstream infile(argv[4]);
if(disc>=0)
{
infile << r1 << endl;
infile << r2 <<endl;
}
else
{
infile << r1 << "+i*" << t1 << endl;
infile << r1 << "-i*" << t1 << endl;
}
infile.close();
string str = "type ";
str.append(argv[4]);
system(str);
}
}
else
{
cout <<"enter values of a,b,c :";
cin >> a >> b >> c;
cout << endl;
float disc = b*b - 4*a*c;
if(disc>0)
{
t1 = t2 = 0;
r1 = (-b+sqrt(disc))/(2*a);
r2 = (-b-sqrt(disc))/(2*a);
cout << "Root 1 is " << r1 << endl;
cout << "Root 2 is " << r2 << endl;
}
else if(disc==0)
{
t1 = t2 = 0;
r1 = (-b)/(2*a);
r2 = (-b)/(2*a);
cout << "Root 1 is " << r1 << endl;
cout << "Root 2 is " << r2 << endl;
}
else
{
r1 = r2 = (-b)/(2*a);
t1 = sqrt(-disc)/(2*a);
t2 = -sqrt(-disc)/(2*a);
if(r1!=0) {
cout << r1 << "+i*" << t1 << endl;
cout << r1 << "-i*" << t1 << endl; }
else {
cout <<"+i*" << t1 << endl;
cout << "-i*" << t1 << endl; }
}
}
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.