Program to solve quadratic expression

Help I need with this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
#include<cmath>
#include<math.h>

using namespace std;


int main()

{

double a, b, c, x1, x2, determinant;

cout<< "Enter a,b and c" <<endl;

cin >> a >> b >> c;
determinant = pow (b, 2) - 4*a*c;

x1 = (-b + sqrt(determinant)) / (2*a);
x2 = (-b - sqrt(determinant)) / (2*a);
 
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;       

return 0;

}


Output:

Enter a,b and c
2 3 4
x1 = -nan
x2 = -nan
4*a*c == 32
pow(b,2) == 9

pow(b,2) - 4*a*c == 9 - 32 == -23

sqrt(-23) == not a number (can't get the sqrt of a negative without complex numbers)
What if the determinant is negative? A square root from a negative number ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<iostream>
#include<cmath>
#include<math.h>
#include <iomanip>  

using namespace std;





void solve()

{
    
    double a,b,c;    // coefficients
    
	cout << "Please enter three floating-point numbers (a b c) to be used as the coefficients in a*x*x + b*x + c == 0: ";

	while (cin>>a>>b>>c) {
		if(a==0) {	// just b*x+c==0
					// easy: x == -c/b
			if (b==0)	// easy: c == 0
				cout << "no root (since x isn't used)\n";
			else
				cout << "x == " << -c/b << '\n';
		}
		else if (b==0) { // a*x*x+c==0
							// we know that a is not zero so, x*x == -c/a
							// if -c/a 0, obviousl x is zero
							// if -c/a is positive, there are two real solutions
							// if -c/a is negative, there are not real solutions
			double ca = -c/a;
			if (ca == 0)
				cout << "x==0\n";
			else if (ca < 0)
				cout << "no real roots\n";
			else
				cout << "two real roots: " << sqrt(ca) << " and " << -sqrt(ca) << '\n';
		}
		else {	// here we finally have to apply the complete formula
				// we know that neither a nor b is zero
			double sq = b*b-4*a*c;
			if (sq==0)
				cout << "one real root: " << -b/(2*a) << '\n';
			else if (sq<0)
				cout << "no real roots\n";
			else
				cout << "two real roots: " << setprecision(12) << (-b+sqrt(sq))/(2*a) << " and " << (-b-sqrt(sq))/(2*a) << '\n';
		}

		cout << "please try again (enter a b c): ";
	}
}

int main()

{
    
    void solve();
    
}




http://coliru.stacked-crooked.com/
Last edited on
Topic archived. No new replies allowed.