- 11. Make a program that calculates the roots of a quadratic equation in the form ax² + bx + c. The program should request the values of a, b and c and make the consistencies, informing the user in the following situations:
If the user enters the value of A equal to zero, the equation is not of the second degree and the program should not ask the other values, being closed;
If the calculated delta is negative, the equation has no real roots. Inform the user and quit the program;
If the calculated delta equals zero the equation has only one real root; inform it to the user;
If delta is positive, the equation has two real roots; inform them to the user;
Bhaskara Formula in C ++
First, we ask for the three coefficients a, b and c.We also declare the delta variable to store delta (really?) and root1 and root2 to store roots.
The first test is to check if a is other than 0, only if we can calculate the roots.
If not, it falls into ELSE and we warn you that the equation does not exist.
Being different from 0, we have to calculate the delta:
From Bhaskara: delta = b² - 4ac
Now, let's test the delta.
If it is negative, we say it has no real roots.
If 0, we calculate the single root: (-b / 2a)
If greater than 0, we calculate the two roots (-b- sqrt(delta))/2a and (-b + sqrt(delta))/2a
See how our code looked:
#include <iostream> #include <cmath> using namespace std; int main() { float a, b, c, delta, root1, root2; cout << "Coefficient a: "; cin >> a; cout << "Coefficient b: "; cin >> b; cout << "Coefficient c: "; cin >> c; if(a != 0){ delta = (b*b) - (4*a*c); if(delta<0){ cout <<"No real roots\n"; } else if (delta==0){ root1=(-b)/(2*a); cout << "One real root: "<<root1<<endl; }else{ root1=(-b - sqrt(delta))/(2*a); root2=(-b + sqrt(delta))/(2*a); cout << "Root 1: "<<root1<<endl; cout << "Root 2: "<<root2<<endl; } }else{ cout <<"a=0, this is not a quadratic equation\n"; } }
C++ challange
Can you solve this question to give complex roots?#include <iostream> #include <cmath> using namespace std; int main() { float a, b, c, delta, root1, root2; cout << "Coefficient a: "; cin >> a; cout << "Coefficient b: "; cin >> b; cout << "Coefficient c: "; cin >> c; if(a != 0){ delta = (b*b) - (4*a*c); if(delta<0){ delta = -delta; cout<<"Root 1: "<<(-b/(2*a))<<"+"<<(sqrt(delta)/(2*a))<<"i\n"; cout<<"Root 2: "<<(-b/(2*a))<<"-"<<(sqrt(delta)/(2*a))<<"i\n"; } else if (delta==0){ root1=(-b)/(2*a); cout << "One real root: "<<root1<<endl; }else{ root1=(-b - sqrt(delta))/(2*a); root2=(-b + sqrt(delta))/(2*a); cout << "Root 1: "<<root1<<endl; cout << "Root 2: "<<root2<<endl; } } else cout <<"a=0, this is not a quadratic equation\n"; return 0; }
No comments:
Post a Comment