java—有人能告诉我如何编写和重写方法,以便找到最多6个百分比输入的几何平均值吗

rpppsulh  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(288)

我不熟悉定义方法和重写方法,如果可以,请向我解释。
这就是我目前所拥有的。
我需要允许用户输入1-6年以及每年增加或减少的百分比,然后我需要找到这些数字的几何平均数。

import java.util.Scanner;
public class GeometricMean_slm
{
//not sure if this is neccessary or proper
   public double average;
   public double y1;
   public double y2;
   public double y3;
   public double y4;
   public double y5;
   public double y6;
   public static void geometricMean6()
   {
      Scanner keyboard = new Scanner(System.in);
      System.out.println("Enter the length of time of the investment (1 to 6 years):");
      int years = keyboard.nextInt();
      System.out.println("Please enter the percent increase or decrease for each year:");
      double y1 = keyboard.nextInt();
      double y2 = keyboard.nextInt();
      double y3 = keyboard.nextInt();
      double y4 = keyboard.nextInt();
      double y5 = keyboard.nextInt();
      double y6 = keyboard.nextInt();
   }
//neither method will execute when I run
   public void main(String[] args)
   {  
         geometricMean6();
         average = (double)Math.pow(y1 * y2 * y3 * y4 * y5 * y6, .16);
         System.out.println("end"+ average);                
   }      
}

根据用户输入的年份,此代码需要重复1-6次。我还需要程序运行后提示用户再次输入,我不知道怎么做。

jtoj6r0c

jtoj6r0c1#

首先,你的方法没有被执行是因为你的主方法不是静态的,它应该是这样的:

public static void main(String[] args){

     geometricMean6();
     average = (double)Math.pow(y1 * y2 * y3 * y4 * y5 * y6, .16);
     System.out.println("end"+ average);                
}

第二个问题是,您不需要那些从函数“geometricmean”中分配的对象,即使这样,您也应该使它们成为静态的,以便在主函数中访问它们。因为你必须得到几何平均数,我把你的函数从空变为双,为了得到一些结果。具体如下:

public static double geometricMean6()
{
    double result = 1;
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter the length of time of the investment (1 to 6 years):");
    int years = keyboard.nextInt();
    System.out.println("Please enter the percent increase or decrease for each year:");
    double input = keyboard.nextDouble();
    result *= input;
    int i = 1;
    while(i < years){
        input = keyboard.nextDouble();
        i++;
        result *= input;
    }
    result = (double) Math.pow(result, (double) 1 / years);
    return result;
}

为了返回最终结果,我在这里指定了一个双结果。while循环正在实现拥有多个输入的目标。它将尽可能的“年”投入。然后,我将用户输入的所有输入相乘。最后,代码计算函数中的几何平均值并返回结果。这就是为什么在main函数中,您只需调用函数并打印出它返回的结果。具体如下:

public static void main(String[] args)
{

    System.out.println("Average is : " + geometricMean6());

}

希望有帮助。祝您有个美好的一天!

相关问题