### I'm having problems with putting formulas in my code.

Hi, I'm a beginning programmer! I'm learning out of a book, and the part I'm reading right now is all about inputs and outputs. I decided that I wanted to practice what I'd learned so far, so I tried to write a program that did the quadratic formula for me.

I'm fairly certain that my formula is correct, but whenever I put numbers in, the wrong answers come out. I put 1, 6, and 9 in for their respective a, b, and c values. This means that the two x's should be equal to -3. However, it tells me that the values are equal to -19 and 13. What have I done wrong?

 ``12345678910111213141516171819202122232425262728293031323334`` `````` #include using namespace std; int main() { // I declare my a, b, and c as integers*\ because I wanted it to be pretty simple,*\ but I declared the x's as float so they can have decimals. int a, b, c; float x1, x2; //Input of the "a" value cout <<"What does 'a' equal? "; cin >> a; //Input of the "b" value cout << "What does 'b' equal? "; cin >> b; //Input of the "c" value cout << "What does 'c' equal? "; cin >> c; //Quadratic Formula x1= (-b + ((b^2)-(4*a*c))^(1/2))/(2*a); x2= (-b - ((b^2)-(4*a*c))^(1/2))/(2*a); //Numbers are put into the equation and the values of the two x's are given. cout << "x1 is equal to " << x1 <
Last edited on
The `^` operator isn't used for powers, it is actually the bitwise exclusive or XOR.

For b2 use simply`b*b`
(there is also the `pow()` function to raise a number to other powers)
For square root, use the `sqrt()` function
`#include <cmath> ` header for those functions.

Some of your variables are of type `int`. I'd recommend that you use a floating-point type for all the variables in this case. Type `double` would be usual, `float` would work but it's less precise and I'd not recommend it for everyday use.
Where are you calculating x1 and x2? These statements have no use:
 ``12`` ``````x1= (-b + ((b^2)-(4*a*c))^(1/2))/(2*a); x2= (-b - ((b^2)-(4*a*c))^(1/2))/(2*a);``````

Show the actual statements in your program.
Looke here:

http://www.cplusplus.com/doc/tutorial/operators/

to learn what the operators do.

`^` is not power. You need to use the function `pow()` instead:

http://www.cplusplus.com/reference/cmath/pow/?kw=pow

`(1/2)` will result in 0 since it's an integer operation. Use at least one none integer value like `(1.0/2)`
Okay, I fixed it! Thank you for the help!

I wasn't aware of the new header that I needed to use (I guess I jumped ahead a bit of where I thought I was)
Topic archived. No new replies allowed.