Please help. I'm student and now working on the program that can solve quadratic equations. The text that appears on screen and solutions should depend from discriminant, but it doesn't.

Also, if discriminant less than zero, it doesn't show that there are no solutions. Instead it shows "-2147387..."

 ``12345678910111213141516171819202122232425262728`` ``````#include #include using namespace std; int main () { int a, b, c, x, D, result1, result2, result3; cout << "Enter coefficient of x^2: " << endl; cin >> a; cout << "Enter coefficient of x: " << endl; cin >> b; cout << "Enter the third component: " << endl; cin >> c; D = ( b * b ) - ( 4 * a *c ); if (D > 0) cout << "This equation has 2 solutions." << endl; result1 = ( 0 - b + sqrt (D) ) / (2 * a); cout << "The first solution is: " << result1 << endl; result2 = ( 0 - b - sqrt (D) ) / (2 * a); cout << "The second solution is: " << result2 << endl; if (D = 0) cout << "This equation has only solution." << endl; result3 = ( 0 - b ) / (2 * a); cout << "The solution is: " << result3 << endl; if (D < 0) cout << "This equation has no solutions." << endl; }``````
Last edited on
You're missing braces from your solutions. There's also the odd syntax error.

 ``123456789101112131415`` ``````if( D > 0 ) { // Discriminant greater than zero // Two real solutions code here } else if ( D == 0 ) { // Discriminant is zero // Code for the one real solution here } else { // Discriminant is less than zero // No real roots }``````
The variables should be of type `double` instead of `int`.

`if (D = 0)` here the `=` is the assignment operator, it should instead be `==` to test for equality.

The header should be `#include <cmath> ` rather than `<math.h>`
Thanks, now it works better, but in all three situations after the correct text it shows "This equation has no solutions".

Here's edited code:
 ``12345678910111213141516171819202122232425262728293031323334`` ``````#include #include using namespace std; int main () { int a, b, c, x, D, result1, result2, result3; cout << "Enter coefficient of x^2: " << endl; cin >> a; cout << "Enter coefficient of x: " << endl; cin >> b; cout << "Enter the third component: " << endl; cin >> c; D = ( b * b ) - ( 4 * a *c ); if (D > 0) { cout << "This equation has 2 solutions." << endl; result1 = ( 0 - b + sqrt (D) ) / (2 * a); cout << "The first solution is: " << result1 << endl; result2 = ( 0 - b - sqrt (D) ) / (2 * a); cout << "The second solution is: " << result2 << endl; } else if (D == 0) { cout << "This equation has only solution." << endl; result3 = ( 0 - b ) / (2 * a); cout << "The solution is: " << result3 << endl; } else; { cout << "This equation has no solutions." << endl; } }``````
Last edited on
`else (D < 0);`
You have a stray terminator (;).
Line 30 `else;` remove the semicolon
Line 8, change `int` to `double`
Line 2, change `<math.h>` to `<cmath>`
Last edited on
Oh, thanks a lot! Now it's working fine. :)
Topic archived. No new replies allowed.