【发布时间】:2013-11-18 06:57:15
【问题描述】:
我想知道如何正确计算“平均步数等于”,因为 step/N 在 main 方法中不起作用。如果我有 100/N,我的代码可以正常运行,但是我不确定如何总结 TestWalk 方法中的步骤,然后返回到 main。谢谢!
class Test {
static int TestWalk() {
int location = 5;
int steps = 0;
while (location != 0 && location !=10)
{
int direction = (int)(Math.random()*2);
if (direction == 0)
{
location = location - 1;
}
if (direction == 1)
{
location = location + 1;
}
steps = steps + 1;
}
if (location == 0)
{
System.out.println ("Time for a walk!");
System.out.println ("Took " + steps + " steps, and ");
System.out.println ("Landed at HOME\n");
}
else
{
System.out.println ("Time for a walk!");
System.out.println ("Took " + steps + " steps, and ");
System.out.println ("Landed in Hospital\n");
}
return steps; }
public static void main (String [] args) {
final int N = 5;
for(int i = 0; i<N; i++)
TestWalk();
System.out.println ("Average # of steps equals " + steps/N);
}
}
【问题讨论】:
标签: java random parameters while-loop return