Nov 27, 2010 at 6:45pm UTC
remove 'void' when you call solveQuadratic() in your main-function.
Nov 27, 2010 at 7:09pm UTC
Thanks a lot for the quick reply, hannes! I use the solver on equations like ax^2+bx+c. But it gives me some strange answers like:
a=1, b=5, c=9
and I get x1 = -1.#IND and for x2 the same as x1!
What could the problem be ?
Last edited on Nov 27, 2010 at 7:14pm UTC
Nov 28, 2010 at 3:54am UTC
Look after the pow function on lines 17 and 18. You have an extra '*'. Also, beware of negative roots. Standard functions won't handle complex numbers.
Nov 28, 2010 at 6:43am UTC
Also, a small note. By convention when you need to square a number you should just use x*x rather than pow(x,2).
Nov 28, 2010 at 4:10pm UTC
Thank a lot! Now it works!
Here`s the final code:
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 65 66 67 68 69 70 71 72 73 74
#include<iostream>
#include<math.h>
using namespace std;
double a;
double b;
double c;
double top;
double top2;
double bottom;
double x;
double x2;
void solvequadratic(){
top=-b+sqrt(pow(b,2)-4*a*c);
top2=-b-sqrt(pow(b,2)-4*a*c);
bottom=2*a;
x=top/bottom;
x2=top2/bottom;
}
int main(){
int again;
cout << "This program solves quadratic equations!" << endl;
cout << endl;
cout << "ax^2 + bx + c = 0" << endl;
cout << endl;
cout << "Enter a: " << endl;
cin >> a;
while (a==0){
cout << "Please, enter a again: " << endl;
cin >> a;
}
cout << "Enter b: " << endl;
cin >> b;
cout << "Enter c: " << endl;
cin >> c;
solvequadratic();
cout << "x1 = " << x << endl;
cout << "x2 = " << x2 << endl;
cout << endl;
cout << "Do you want to try again?(1-yes/2-no)" << endl;
cin >> again;
while (again==1){
main();
again=0;
}
if (again==2){
exit(1);
}
getchar();
return 0;
}
Last edited on Nov 28, 2010 at 4:11pm UTC
Nov 29, 2010 at 9:51pm UTC
You also may want to use #include <complex>
becasue sooner or later you will inevitably get one that requires this library. This is not really necessary, but could be useful when you have one of those tricky problems with imaginary numbers.