I'm trying to code a program in C++ to: ask for 3 integers, display them, and depending on the numbers, use the if code to output results.
if the equation is quadratic (a is nonzero) and the roots are real (b2-4ac>=0), compute the root(s) and display them with 3 digits to the right of the decimal and labels
if the equation is not quadratic (a is zero), compute the root and display it with 3 digits to the right of the decimal and a label
if the equation is quadratic but the roots are complex (b2-4ac<0), then display a message stating that the roots are complex and will not be computed
#include <iostream>
#include <math.h>
usingnamespace std;
int main()
{
int a;
int b;
int c;
double quadratic1;
double quadratic2;
double rootscheck = 0;
cout << "Type three values." << endl;
cin >> a >> b >> c ;
cout<< a << b << c << endl;
if (a != 0 && rootscheck >= 0)
{
quadratic1 = (-b + sqrt(b*b - 4*a*c))/2*a;
quadratic2 = (-b - sqrt(b*b - 4*a*c))/2*a;
cout << quadratic1 << quadratic2;
}
else
{
if (a == 0)
{
quadratic1 = (-b + sqrt(b*b - 4*a*c))/2*a;
quadratic2 = (-b - sqrt(b*b - 4*a*c))/2*a;
cout << quadratic1 << quadratic2;
}
else
cout << "Roots are complex and will not be computed.";
}
return 0;
}
It compiles, but only runs a small portion. When I input numbers, it does the " cout<< a << b << c << endl;" step, then stops. How can I make it run the rest?
1. (Minor) <cmath> instead of <math.h> ; doesn't matter too much since we're using all of namespace std.
2. Use setf and precision to set the decimal points to 3.
3. Use logical variable names to clearly depict what you're storing, like booleans for whether things are real.
4. You have a logic error with .../2*a . It should be .../(2*a) so that it divides by the product of 2 and a, instead of dividing by 2 and then multiplying by a.
5. Check for extra edge cases, like only one root even if quadratic (constants 1 2 1 for example)