0

I am trying to write a for loop in the second version which produce the same result in the original code but i am not sure how to get -400,-200,-400 in sequential order.
original code:

p->m_p[0] = randFloat(-400.0f, 400.0);
p->m_p[1] = randFloat(-200.0f, 200.0);
p->m_p[2] = randFloat(-400.0f, 400.0);

second version:

float x = -800;
float y = 800;

for(int i = 0; i < 4; i++)
{
plNew->m_fPosition[i] = randFloat(x / 2,y / 2); 
}
4

5 回答 5

2

如果您需要它在 C(或 C++11 之前的 C++)中工作,这将工作:

#define NUMBER_OF_VALUES 3

float bounds[NUMBER_OF_VALUES] = { 400.0f, 200.0f, 400.0f };

for (int i = 0; i < NUMBER_OF_VALUES; i++)
{
  plNew->m_fPosition[i] = randFloat(-bounds[i], bounds[i]); 
}

您可以扩展它以使 NUMBER_OF_VALUES 为 4 或更大的数字,只要您bounds[NUMBER_OF_VALUES]使用所需的常量初始化 的所有成员。一个很好的特点是常量序列可以是任何你喜欢的,不限于交替 400、200、400 或任何其他常规序列。

于 2015-01-09T22:49:35.733 回答
1

像这样的东西?

for (int i = 0; i < 4; i++) {
    float x, y;

    if (i % 2) {
        x = -400.0f;
        y = 400.0f;
    } else {
        x = -200.0f;
        y = 200.0f;
    }

    p->m_p[i] = randFloat(x, y);
}
于 2015-01-09T22:38:03.397 回答
0

我建议保持简单,使用如下内容:

const float arr3[] = {-400.0f, -200.0f, -400.0f};

for(int i = 0; i < 3; i++)
{
    plNew->m_fPosition[i] = arr3[i]; 
}
于 2015-01-09T23:08:54.173 回答
0

关于什么?

float x = -800;
float y = 800;

for(int i = 0; i < 4; i++)
{
    float z = 2.0 * ((float)((i + 1) % 2 + 1));
    plNew->m_fPosition[i] = randFloat(x / z, y / z); 
}
于 2015-01-09T22:40:42.697 回答
0
float x = -400;
float y =  400;

for(int i = 0; i < 3; i++)
{
    plNew->m_fPosition[i] = randFloat(x / (1 + (i & 1)), y / (1 + (i & 1))); 
}
于 2015-01-10T06:32:40.650 回答