gpt4 book ai didi

java - 根据返回值计算平均值

转载 作者:太空宇宙 更新时间:2023-11-04 15:24:14 25 4
gpt4 key购买 nike

我想知道如何正确计算“平均步骤数等于”,因为步骤/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);
}
}

最佳答案

您需要在main()中有一个steps变量,它将包含从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);

关于java - 根据返回值计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20041885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com