我想知道如何正确计算“平均步数等于”,因为步骤/ N在主方法中不起作用。如果我有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);
}
}
答案 0 :(得分:0)
您需要在main()
中包含一个步骤变量,其中包含从TestWalk()
返回的所有步骤的总和;方法
int steps = 0; // this is local to main and has nothing do with the steps in TestWalk() method
for(int i = 0; i<N; i++) {
steps += TestWalk(); // steps will keep the sum of all the steps
}
System.out.println ("Average # of steps equals " + steps/N);
答案 1 :(得分:0)
将你的方法主要归结为:
int steps = 0;
for(int i = 0; i<N; i++)
steps += TestWalk();
System.out.println ("Average # of steps equals " + steps/N);
答案 2 :(得分:0)
试试这个..
public static void main (String [] args) {
final int N = 5;
int total = 0;
for(int i = 0; i<N; i++)
total+= TestWalk();
System.out.println ("Average # of steps equals " + total/N);
}