Created
August 21, 2021 19:53
-
-
Save Abiola-Farounbi/fcb7646b9b89338a07608b372b426127 to your computer and use it in GitHub Desktop.
This program calculates the roots of a quadratic equation in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cmath> | |
using namespace std; | |
//Function call by reference using pointers | |
void AskForValues(double *a_ptr, double *b_ptr,double *c_ptr) | |
{ | |
cout << endl << "Enter your values" ; | |
cout << endl << "Enter coefficient a " ; | |
cin >> *a_ptr ; | |
cout << endl << "Enter coefficient b " ; | |
cin >> *b_ptr ; | |
cout << endl << "Enter coefficient c " ; | |
cin >> *c_ptr ; | |
} | |
void CalculateResult(double a, double b, double c) | |
{ | |
double root1, root2; | |
// to determine the type of root | |
double value = pow(b,2) - (4*a*c); | |
cout << value << endl ; | |
if (value > 0){ | |
root1 = (-b + sqrt(value)) / (2*a); | |
root2= (-b - sqrt(value)) / (2*a); | |
cout << "Roots are real and different." << endl; | |
cout << "\n The Roots of the equation are : " << root1 << " , " << root2 << endl ; | |
} | |
else if(value == 0){ | |
root1 = (-b ) / (2*a); | |
root2 = (-b ) / (2*a); | |
cout << "Roots are real and same." << endl; | |
cout << "\n The Roots of the equation are : " << root1 << " , " << root2 << endl ; | |
} | |
else if(value < 0) // For complex roots: Imaginary and real | |
{ | |
root1 = (-b ) / (2*a); | |
root2 = (-b ) / (2*a); | |
cout << "Roots are complex and different." << endl; | |
cout << root1 << "+i " << (sqrt(-(value))/ (2*a)) << endl; | |
cout << root1 << "-i " << (sqrt(-(value))/ (2*a)) << endl; | |
} | |
} | |
int main() | |
{ | |
// Intialize the variables for the parameter and array fpr the result | |
double a,b,c, result[2]; | |
char answer; | |
cout << "Welcome to Quadratic Equation Calculator" << endl ; | |
do{ | |
AskForValues(&a,&b,&c); | |
CalculateResult(a,b,c); | |
// To Calculate again | |
cout << endl << "Do you want to do calculate again? (Y = Yes & N = No)" << endl; | |
cin >> answer; | |
} | |
while(answer == 'y' || 'Y'); | |
system("PAUSE"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment