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?
#include <iostream>
usingnamespace 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 <<endl;
cout << "x2 is equal to " << x2 << endl;
system("pause");
return 0;
}
The ^ operator isn't used for powers, it is actually the bitwise exclusive or XOR.
For b2 use simplyb*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.