Basically for this assignment we needed to make a program that would solve quadratic equations using the quadratic formula.
I got most of the program down but i'm constantly having trouble with the last else statement. I want it so that whenever i input anything other than a number, it would give the output, "Sorry bad input" But instead whenever i debug and run it, whenever i type in a letter it gives me the wrong output.
I tried reading my book but it didn't help me... Checked some online sources and they only covered it very briefly or it was too complicated for me to understand...
int main (void)
{
double discriminant, A, B, C, Part1, Part2, imaginary1;
bool imaginary, one_solution, Real_Sol, A_Zero, Other;
cout << "This program will provide solutions for an equation of the form" << endl;
cout << right;
cout << setw(40) << "A*x^2 + B*x + C = 0" << endl;
cout << "Where A, B, and C are integers."<<endl ;
cout << "Enter A, B, and C: ";
cin >> A >> B >> C ;
//Equations
discriminant = (B * B) - (4 * A * C);
Part1 = (-B/(2*A));
Part2 = sqrt(discriminant)/(2*A);
imaginary1 = sqrt(fabs(discriminant))/(2*A);
one_solution = (discriminant == 0.0); // If the discriminant is zero, the second term is canceled out.
imaginary = (discriminant < 0.0); // Decide if the solution will be imaginary
Real_Sol = (discriminant > 0.0); // If the discriminant is positive it will give 2 outputs
A_Zero = (A==0); // A is equal to 0(zero)
if (A_Zero)
{
cout << "Cannot divide by zero. Sorry"<<endl;
return(0);
}
else if (one_solution)
{
cout.precision(4);
cout << "The one real solution is x=" << scientific << Part1 <<endl;
return(0);
}
else if (imaginary)
{
cout.precision(4);
cout << "The two imaginary solutions are x="<< scientific << Part1 << "+" << '(' << imaginary1 << ')' << 'i' <<endl;
cout << "and x="<< Part1 << "+" << '(' << imaginary1 << ')' << 'i' <<endl;
return(0);
}
else if (Real_Sol)
{
cout.precision(4);
cout << "The two real solutions are x="<< scientific << Part1+Part2 <<endl;
cout << "and x="<< scientific << Part1-Part2 <<endl;
return(0);
}
Could anybody help or direct me into the right direction? I've been trying to solve this problem for days and couldn't get anywhere.. Any help would be greatly appreciated.
1) Split your cin into three separate lines of code and check for
stream errors between each input (a stream error will occur
if the input is invalid, ie, not a number);
2) Read the user input into strings and parse the input, ensuring
that the input entered is in the format of an integer.
BTW, your A, B, and C are declared as doubles (which means floating
point numbers such as 3.14 will be accepted) but your prompt says
to enter integers.