Okay, I'm developing a program that will solve quadratic equations for users. I have them plug in values for a, b, and c in the following formula: ax^2 + bx +c. This formula probably looks familiar to you guys from highschool. Anyways, for some reason my code outputs completely inaccurate results. Here is my code:
cout<<"Your solutions are: x = ";
cout<<sol1;
cout<<" or x = ";
cout<<sol2<< endl;
system("PAUSE");
return 0;
}
For example, the equation 4x^2 + 5x + 1 comes up with x = -4 and x = -16 when the answers are clearly -1 and -1/4. I'm probably making some really stupid mistake or maybe i messed up the formula but i can't seem to figure it out! Anyways, some help would be nice. And please be gentle i'm new to this. Thanks!
PS. I'm plugging the user input into the quadratic formula just in case you were confused. The quadratic formula can be found here: http://mste.illinois.edu/exner/ncsa/quad/
A possible problem is that ints don't divide very well. E.g. 1 divided by 2 will give you zero (0.5 with the .5 chopped off).
Try it with floats as the input and output.
Also a good principle when doing any maths in C++ is for the answer and every input to all be the same datatype, otherwise you will often get unexpected results.
As has been suggested the problem is integer division. Switch to doubles throughout.
And note that 2 is an integer whereas 2.0 is a double.
Another problem is that you must make sure that sqrt isn't called with a negative parameter. This happens when the quadratic formula has imaginary solutions.
Last edited by nuzzle; July 20th, 2011 at 07:10 AM.
Thank you very much. I changed everything to doubles including the non variable values as well and i got the correct answers. This should make math homework go by a lot faster Thanks to both of you! Cheers!
Don't forget that some teachers will take off points if you don't write down every step.
And, if you miss something in one step, but carry the issue forward, some teachers will give you partial credit (i.e. not penalize you full points because you wrote a '8' down instead of a '7').
Bookmarks