Hello everyone. I'm new to C++ and programming in general, and this class I am taking is throwing me for a loop. I have an assignment where I am supposed to use the quadratic equation, allowing users to enter the values for A, B, and C to come up with an answer.The program runs correctly, giving the prompts needed, and the equation is typed the way my instructor wrote it out for us, but no matter what numbers I use for A, B, and C when I test the program, it always returns the result -1.#J. I can't figure out what I've done wrong. Thank you for any help. It is much appreciated.
cout << fixed << showpoint << setprecision(2); //Sets the floating point
const float X1 = (-B + sqrt(B*B - 4*A*C))/(2*A);
cout << "We will solve for X." << endl;
cout << "Enter a number for A." << endl; //This prompts the user to enter the value for A.
cin >> A;
cout << "Enter a number for B." << endl; //This prompts the user to enter the value for B.
cin >> B;
cout << "Enter a number for C." << endl; //This prompts the user to enter the value for C.
cin >> C;
cout << X1 << endl; //Displays the results
The problem is that you compute X1 before you have got input from the user. An important
thing to remember is that you can use a variable even if you haven't assigned any value to it
explicitly ( if you don't explicitly assign a value to a variable, the variable will hold a random
value ). This property of variables can cause programs to give unexpected results.
Here's a version of your program that should run correctly:
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
usingnamespace std;
float A;
float B;
float C;
void main()
{
cout << fixed << showpoint << setprecision(2); //Sets the floating point
cout << "We will solve for X." << endl;
cout << "Enter a number for A." << endl; //This prompts the user to enter the value for A.
cin >> A;
cout << "Enter a number for B." << endl; //This prompts the user to enter the value for B.
cin >> B;
cout << "Enter a number for C." << endl; //This prompts the user to enter the value for C.
cin >> C;
constfloat X1 = (-B + sqrt(B*B - 4*A*C))/(2*A);
cout << X1 << endl; //Displays the results
}
I looked over the code you listed, and it appears that you moved the formula after the input statements? Was that really all I needed to do? I've been racking my brain over this one for hours now! It's a little funny that it was a simple fix! Thanks for your help.
I ran the program again, and it gives me actual totals instead of gibberish, but the instructor gave us two sets of numbers to run. The first is A = 2.0, B = 3.0, and C = -65.0. The second is A = 4.0, B = 5.0, and C = -174.0. He has a hint listed that one set should yield the result -6.5, but my answers end up being 5.00 and 6.00 respectively. I guess I'm still doing something incorrectly.