2011-01-09 61 views
1

之间减量这是令人尴尬的,但:如何增加和两个值

让说我要1添加X,直到它达到100在这一点上,然后我想从X减去1,直到达到1 。然后我想将1加到x直到达到100,依此类推。

有人可以提供一些简单的伪代码给这个问题,让我觉得特别愚蠢。

谢谢:)


编辑1

道歉!我让我的例子太简单了。我居然会使用随机数在每次迭代递增,因此需要反应(X == 100)将不会为x工作一定会走高于100和低于1

+1

你能不能用一个例子来阐述你的编辑? – 2011-01-09 04:22:52

回答

0
int ceiling = 100; 
int floor = 1; 
int x = 1; 
int step = GetRandomNumber(); //assume this isn't 0 

while(someArbitraryCuttoffOrAlwaysTrueIDK) { 
    while(x + step <= ceiling) { 
     x += step; 
    } 
    while(x - step >= floor) { 
     x -= step; 
    } 
} 

或者是更简洁(在是不太清楚的风险):

while(someArbitraryCuttoffOrAlwaysTrueIDK) { 
    while((step > 0 && x + step <= ceiling) || (step < 0 && x + step >= floor)) 
    { 
     x += step; 
    } 
    step = step * -1; 
} 

或者:

while(someArbitraryCuttoffOrAlwaysTrueIDK) { 
    if((step > 0 && x + step > ceiling) || (step < 0 && x + step < floor)) 
    { 
     step = step * -1; 
    } 
    x += step; 
} 
2

这里是数学方法:

for(int i=0;i<10000000;i++) 
    print(abs(i%200-100)) 

算法中的方式:

int i = 1; 
while(1) 
{ 
while(i<100)print(i++); 
while(i>1)print(--i); 
} 

随机更新:

int i = 1; 
while(1) 
{ 
while(i<100)print(i=min(100,i+random())); 
while(i>1)print(i=max(1,i-random())); 
} 
+0

对于第一个,你得到序列100-> 0-> 100-> ...而不是1-> 100-> 1 - > ... – 2011-01-09 10:00:36

0

C#:

Random rnd = new Random(); 
int someVarToIncreaseDecrease = 0; 
bool increasing = true; 

while(true) { 
    int addSubtractInt = rnd.Next(someUpperBound); 

    if (increasing && (someVarToIncreaseDecrease + addSubtractInt >= 100)) 
     increasing = false; 
    else if (!increasing && (someVarToIncreaseDecrease - addSubtractInt < 0)) 
     increasing = true; 

    if (increasing) { 
     someVarToIncreaseDecrease += addSubtractInt; 
    } 
    else { 
     someVarToIncreaseDecrease -= addSubtractInt; 
    } 
}