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



我不熟悉定义方法和重写它们,如果可以的话,请向我解释。

这就是我到目前为止所拥有的
我需要允许用户输入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次,具体取决于用户输入的年份。我还需要程序在运行后提示用户进行另一次输入,我不知道该怎么做

首先,您的方法没有被执行的原因是您的主方法不是静态的,它应该看起来像这样:

public static void main(String[] args){
geometricMean6();
average = (double)Math.pow(y1 * y2 * y3 * y4 * y5 * y6, .16);
System.out.println("end"+ average);                
}      

那么第二个问题是,你不需要那些在函数"之外分配的;geometricMean",即使你这样做了,你也应该让它们成为静态的,以便在你的主函数中访问它们。由于你必须得到几何平均值,我把你的函数从void改为double,以便返回一些结果。如下所示:

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

在这里,我指定了一个双重结果,以便返回最终结果。而循环实现了具有多个输入的目标。它将一直走到";年";输入然后,我将用户输入的所有输入相乘。最后,代码计算函数中的几何平均值并返回结果。这就是为什么在主函数中,您所要做的就是调用函数并打印出它返回的结果。如下所示:

public static void main(String[] args)
{
System.out.println("Average is : " + geometricMean6());
}

希望它能有所帮助。祝你今天愉快!

最新更新