In: Computer Science
How would I write a code from this following word problem?
3. Use the pow() and sqrt() functions to compute the roots of a quadratic equation. Enter the three coefficients with a single input statement. Warning: if you give sqrt() a negative value, the function cannot produce a valid answer.
Note These both are mathematical function so you need to #include <math.h> header file in your code in order to run a error free code
pow() function is used to calculate power of a number i.e we want a^b then pow will be like
Syntax ----> pow(a,b)
Example you want 2^3 so you will write pow(2,3) and ans will be 8
Sqrt() Function is used to find square root of a number And it is used as
Syntax --- >sqrt(number)
For example you root 4 value so write as
sqrt(4) ans will be 2
To calculate roots of a quadratic equation we use quadratic formula i.e
x1=-b + sqrt(b^2- 4ac) /2a
x2=x1=-b - sqrt(b^2- 4ac) /2a
C++ code for finding roots of a number
#include<iostream.h>
#include<math.h> // so that we can use sqrt and pow function
using namespace std;
int main()
{
float a ,b ,c ,D; // These are coefficients of the quadratic equation ax^2+b*x+c
float root1,root2;
cout<"Enter the three coefficients of the Equation a,b c";
cin>>a>>b>>c;
// Now calculate D for the equation i.e discriminant which is D=pow(b,2)-4*a*c
//Three cases are there
//1. D=0 means equation having equal roots
// 2. D>0 means equation having real and distinct roots
// 3. D<0 the case that you said function will not give a valid ans as roots are imaginary in this case
// Applying above 3 in code
D=pow(b,2)-4*a*c;
//Check for D
if(D>0 || D=0) // Case 1 and Case 2 in Case 1 root 1=root 2
{
root1=( -b + sqrt(D) ) /2a;
root2 = (-b - sqrt(D) ) /2a;
cout<<"First Root is "<<root1<<endl;
cout<<"Second Root is "<<root2<<endl;
}
else // this is the case when D<0 and we are giving a negative value to sqrt() function
{
cout<<"Value of D is negative so Function" cannot produce a valid answer as roots are imaginary";
}
return 0 ;
}