Infinite Possibilities
Infinite Possibilities

Reputation: 7466

c++ problem, maybe with types

I have a little problem in my code. The variables don't want to change their values. Can you say why? Here is my code:

vector<coordinate> rocks(N);
double angle;
double x, y;
// other code
while (x > 1.0 || x < -1.0 || y > 1.0 || y < -1.0) {
    angle = rand() * 2.0 * M_PI;
    cout << angle << endl;
    cout << rocks[i - 1].x << endl;
    cout << rocks[i - 1].y << endl;
    x = rocks[i-1].x + r0 * cos(angle);
    y = rocks[i-1].y + r0 * sin(angle);
    cout << x << endl;
    cout << y << endl << endl;
}
// other code

And the result on the console is:
6.65627e+09
0.99347
0.984713
1.09347
0.984713

1.16964e+09
0.99347
0.984713
1.09347
0.984713

As you see the values of x, y variables doesn't change and this while be an infinity loop. What's the problem? What do you think?

Upvotes: 0

Views: 150

Answers (3)

sjchoi
sjchoi

Reputation: 628

angle you are generating seems to be extremely large. I'm assuming you want to generate angle between 0 and 2*pi. Check to see if rand() is returning a number between 0 to 1 and also check to see what M_PI is.

If that doesn't help, find out what each elements are by adding more cout

Upvotes: 0

A. Levy
A. Levy

Reputation: 30586

Perhaps your rand() function isn't defined. Sometimes failing to include the correct headers results in an odd default rand being called, and it may always return the same number. This is just off the top of my head, but I would check in that direction.

Actually, I don't ever remember this happening with rand, but I think I've seen it happen with the trigonometric functions if you don't include math.h. Though that may be a compiler specific quirk.

Upvotes: 0

CB Bailey
CB Bailey

Reputation: 791779

Why are you expeciting x and y to change? You assign to them the value of a calculation that doesn't change?

rand() * 2.0 * M_PI is always a multiple of 2 * pi (as far as a double can represent) so cos(angle) will be 1 and sin(angle) will be 0.

Upvotes: 12

Related Questions