【问题标题】:Computing average from return values从返回值计算平均值
【发布时间】: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


    【解决方案1】:

    您需要在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);
    

    【讨论】:

    • 谢谢!你们太棒了!!
    • @user3003605 - 如果对您有帮助,请回答 accept! :)
    【解决方案2】:

    将 main 中的 for 方法更改为:

    int steps = 0;
    for(int i = 0; i<N; i++)
       steps += TestWalk();
    System.out.println ("Average # of steps equals " + steps/N);
    

    【讨论】:

      【解决方案3】:

      像这样尝试..

           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);
      }
      

      【讨论】:

        猜你喜欢
        • 2015-03-30
        • 1970-01-01
        • 1970-01-01
        • 2012-06-19
        • 1970-01-01
        • 1970-01-01
        • 2013-01-14
        相关资源
        最近更新 更多