[英]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 6.65627e + 09
0.99347 0.99347
0.984713 0.984713
1.09347 1.09347
0.984713 0.984713
1.16964e+09 1.16964e + 09
0.99347 0.99347
0.984713 0.984713
1.09347 1.09347
0.984713 0.984713
As you see the values of x, y variables doesn't change and this while be an infinity loop. 如您所见,x的值不变,y变量不变,这是一个无限循环。 What's the problem?
有什么问题? What do you think?
你怎么看?
Why are you expeciting x
and y
to change? 为什么您期望
x
和y
发生变化? 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. rand() * 2.0 * M_PI
始终是2 * pi的倍数(据双rand() * 2.0 * M_PI
表示),因此cos(angle)
将为1, sin(angle)
将为0。
Perhaps your rand() function isn't defined. 也许您的rand()函数没有定义。 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. 实际上,我永远都不会记得rand发生的这种情况,但是我想如果您不包括math.h,我已经看到三角函数会发生这种情况。 Though that may be a compiler specific quirk.
虽然那可能是编译器特有的怪癖。
angle
you are generating seems to be extremely large. 您生成的
angle
似乎非常大。 I'm assuming you want to generate angle
between 0
and 2*pi
. 我假设您想生成
0
到2*pi
之间的angle
。 Check to see if rand()
is returning a number between 0 to 1 and also check to see what M_PI
is. 检查
rand()
是否返回0到1之间的数字,并检查M_PI
是什么。
If that doesn't help, find out what each elements are by adding more cout
如果这样做没有帮助,请通过添加更多
cout
找出每个元素是什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.