這是一個我堅持上學的計劃。無法弄清楚爲什麼它不會給我一個平均和最大的。該程序運行50次就像我想要的,但不會增加移動和總數的值。不知道爲什麼這不起作用
import java.util.*;
public class RandomWalk {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random rand = new Random();
int location;
double average;
int greatest=0;
int moves = 0;
int total = 0;
int step;
for (int i = 0; i < 50; i++) {
location = 4;
step = rand.nextInt((2 - 1) + 1) + 1;
while (location < 1 || location > 7) {
moves ++;
if (step == 2){
location ++;
} else {
location --;
}
if (moves > greatest) {
greatest = moves;
total += moves;
}
}
}
average = total/50;
System.out.println("The greatest number of steps: " + greatest);
System.out.println("The average number of steps: " + average);
}
}
修復for循環,但它仍然不給我平均和最大。
作爲while (location < 1 || location > 7)
它應該運行,直到人站在位置1和位置7
這裏的問題是我得到:
在「隨機漫步」,一個人被放置在七米長的橋樑的中心。每個步驟隨機向前或向後移動1米的人。 創建一條隨機步道,確定在走下橋之前,人步行了多少步。申請平均50次審判,並顯示平均和最多的步驟。
感謝幫助...
如果我把它改成這樣:`進口的java.util。*;
公共類RandomWalk2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random rand = new Random();
double average;
int greatest=0;
int moves;
int total = 0;
int step;
step = rand.nextInt((2 - 1) + 1) + 1;
int location; //location of man on bridge
for(int i = 0; i < 50; i++)
{
moves = 0;
moves++;
location = 4;
total += moves;
while(true)
{
if (step == 2) {
location++;
} else {
location--;
}
if((location < 1) || (location > 7)) break;
}
if(moves > greatest) {
greatest = moves;
}
}
average = total/50;
System.out.println("The greatest number of steps: " + greatest);
System.out.println("The average number of steps: " + average);
}
}
` 那麼它運行50次,但只佬移動一個站,所以我的最大平均總是顯示爲1
現在將是一個偉大的時間去學習使用調試器。或者,使用筆和紙。 –