In: Computer Science
IN C++
The Quadratic equation is used to solve for the variable x where the function evaluates to zero. However there is actually two answers returned by the quadratic equation. Can we solve for the quadratic equation using just one call to a function you write?
Hint : create a function that does not 'return' anything. Takes three parameters a,b,c as double.s
And had two more parameters that are passed by reference to two doubles that are the two answers from the quadratic equation.
Look on line or in your old math books to who that you tested this with at least three test cases.
this is my code so far I don't know how I should do the next function or if i should just call it in the main already.
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
void Quad (double a, double b, double c, double &plusValue, double &minusValue)
{
plusValue = (-b + sqrt(b * b - 4 * a * c)) / (2 *a);
minusValue = (-b - sqrt(b * b - 4 * a * c)) / (2 *a);
}
void Quad(double a, double b, double c, double minus, double plus)
{
}
int main()
{
}
You should just call it in the main already. Your code is fine but it will not work in the case where (b * b - 4 * a * c) becomes negative as you will get complex roots so i have also added that case in code no 2:
code 1 :
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
void Quad (double a, double b, double c, double &plusValue, double &minusValue)
{
plusValue = (-b + sqrt(b * b - 4 * a * c)) / (2 *a);
minusValue = (-b - sqrt(b * b - 4 * a * c)) / (2 *a);
}
int main()
{
double plusValue=0,minusValue=0,a,b,c;
cout << "Enter coefficients a, b and c of quadratic Equation
(ax2 + bx + c = 0 ): \n";
cin >> a >> b >> c;
Quad(a,b,c,plusValue,minusValue);
cout<<"Roots of Euation : "<<plusValue<<"
"<<minusValue;
}
code Snippet:-
OUTPUT:-
CODE CONSIDERING THE CASE WHERE WE GET NEGATIVE discriminant:-
Code no 2:-
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
void Quad (double a, double b, double c, double &plusValue,
double &minusValue,int &flag)
{
plusValue = (-b + sqrt(b * b - 4 * a * c)) / (2 *a);
minusValue = (-b - sqrt(b * b - 4 * a * c)) / (2 *a);
if((b * b - 4 * a * c)<0)
{
flag=1;
plusValue=-b/(2*a);
minusValue=sqrt(-(b * b - 4 * a * c));
}
}
int main()
{
double plusValue=0,minusValue=0,a,b,c;
int flag=0;
cout << "Enter coefficients a, b and c of quadratic Equation
(ax2 + bx + c = 0 ): \n";
cin >> a >> b >> c;
Quad(a,b,c,plusValue,minusValue,flag);
if(flag==1)
{
cout << "Roots are complex and different." <<
endl;
cout << plusValue << "+" << minusValue <<
"i" << endl;
cout << plusValue << "-" << minusValue <<
"i" << endl;
}
else{
cout<<"Roots of Euation : "<<plusValue<<"
"<<minusValue;}
}
Code snippet:-
Code Output:-