2014-02-12 49 views

回答

2

如果你想-1的甚至分佈和1,您可以使用:

Random rand = new Random(); 

while({condition}) 
{ 
    int next = rand.Next(2) == 0 ? -1 : 1; 
} 
+0

爲什麼不做一個簡單的數學運算?我想這個:'rand.Next(2) - 1' – aloisdg

+0

@aloisdg會給你-1或0,而不是-1或1. –

+0

是的你是對的。這個怎麼樣:'rand.Next(2)* 2 - 1' – aloisdg

0

有:

var r=new Random(); 
int direction = (r.Next(2) == 1 ? 1 : -1); 

r.Next(2)將產生無論是0或在每次調用一個1

或:

int directions[] = {1, -1}; 
int direction = directions[r.Next(2)];