之間減量這是令人尷尬的,但:如何增加和兩個值
讓說我要1添加X,直到它達到100在這一點上,然後我想從X減去1,直到達到1 。然後我想將1加到x直到達到100,依此類推。
有人可以提供一些簡單的僞代碼給這個問題,讓我覺得特別愚蠢。
謝謝:)
編輯1
道歉!我讓我的例子太簡單了。我居然會使用隨機數在每次迭代遞增,因此需要反應(X == 100)將不會爲x工作一定會走高於100和低於1
之間減量這是令人尷尬的,但:如何增加和兩個值
讓說我要1添加X,直到它達到100在這一點上,然後我想從X減去1,直到達到1 。然後我想將1加到x直到達到100,依此類推。
有人可以提供一些簡單的僞代碼給這個問題,讓我覺得特別愚蠢。
謝謝:)
編輯1
道歉!我讓我的例子太簡單了。我居然會使用隨機數在每次迭代遞增,因此需要反應(X == 100)將不會爲x工作一定會走高於100和低於1
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;
}
這裏是數學方法:
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()));
}
對於第一個,你得到序列100-> 0-> 100-> ...而不是1-> 100-> 1 - > ... – 2011-01-09 10:00:36
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;
}
}
你能不能用一個例子來闡述你的編輯? – 2011-01-09 04:22:52