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?

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
 #include <iostream>

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 <<endl;
	cout << "x2 is equal to " << x2 << endl;

system("pause");
return 0;
}
Last edited on
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.
Where are you calculating x1 and x2? These statements have no use:
1
2
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.