finding x using loop

hello I'm a beginner and I've been trying to write a program that finds the approximate x in this equation using for loop. y= 3x^3 - 7x- 11 (0 < x < 3)

#include <iostream>
using namespace std;

int main()
{
double x;
double y = 3 * x ^ 3 - 7 * x - 11;
for (0 < x < 3; x++)
y == 0;
cout << x;

system("pause");
return 0;

}

I've done this so far but something seems to be wrong. How can I fix it?
Thanks for the help.
Last edited on
First, use of code tags makes it easier to read code.
See http://www.cplusplus.com/articles/jEywvCM9/

Your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
  double x;
  double y = 3 * x ^ 3 - 7 * x - 11;

  for (0 < x < 3; x++)
    y == 0;

  cout << x;
  system("pause");
  return 0;
}


something seems to be wrong

Compiler is your friend. It (should) give warnings and errors and even point to the offending code lines. Some compilers have to be told to be more verbose tham what they are by default. When there are many errors, start from the first.

The reference documentation is your friend too. http://www.cplusplus.com/reference/
(But at first you won't know what to seek.)

Thus, tutorial might help. See http://www.cplusplus.com/doc/tutorial/


You do calculate value of y at line 7, but you don't have x yet. Since x is undefined, y is undefined too. You have to assign some value to x and then calculate the y. You have to repeat the calculation with every value of x that you are interested in.

The C++ does have operator^, but it is not power. There is function pow(), but x^3 you could write: x*x*x

The for loop has a bit different syntax.
See http://www.cplusplus.com/doc/tutorial/control/

The 0 < x < 3 is like writing
1
2
bool tmp = 0 < x;
tmp < 3

tmp is either true or false. What are (true < 3) and (false < 3)?

If you want to know whether both conditions are true, you have to write:
(0 < x) and (x < 3)
That gives you true or false.

Your loop, however, could perhaps be a while loop.

The only statement in your loop is y == 0;
That again returns either true or false, but you don't store the result anywhere.
One could write bool zero = (y == 0); and then use the variable zero.

There is on extra problem in y==0. The y is a double. Equality comparison of floating point values is far from trivial. You could try abs(y) < epsilon, where epsilon is a small value. A websearch should explain more.
thank you so much :)
Topic archived. No new replies allowed.