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

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

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

  1. import java.util.Scanner;
  2. public class GeometricMean_slm
  3. {
  4. //not sure if this is neccessary or proper
  5. public double average;
  6. public double y1;
  7. public double y2;
  8. public double y3;
  9. public double y4;
  10. public double y5;
  11. public double y6;
  12. public static void geometricMean6()
  13. {
  14. Scanner keyboard = new Scanner(System.in);
  15. System.out.println("Enter the length of time of the investment (1 to 6 years):");
  16. int years = keyboard.nextInt();
  17. System.out.println("Please enter the percent increase or decrease for each year:");
  18. double y1 = keyboard.nextInt();
  19. double y2 = keyboard.nextInt();
  20. double y3 = keyboard.nextInt();
  21. double y4 = keyboard.nextInt();
  22. double y5 = keyboard.nextInt();
  23. double y6 = keyboard.nextInt();
  24. }
  25. //neither method will execute when I run
  26. public void main(String[] args)
  27. {
  28. geometricMean6();
  29. average = (double)Math.pow(y1 * y2 * y3 * y4 * y5 * y6, .16);
  30. System.out.println("end"+ average);
  31. }
  32. }

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

jtoj6r0c

jtoj6r0c1#

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

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

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

  1. public static double geometricMean6()
  2. {
  3. double result = 1;
  4. Scanner keyboard = new Scanner(System.in);
  5. System.out.println("Enter the length of time of the investment (1 to 6 years):");
  6. int years = keyboard.nextInt();
  7. System.out.println("Please enter the percent increase or decrease for each year:");
  8. double input = keyboard.nextDouble();
  9. result *= input;
  10. int i = 1;
  11. while(i < years){
  12. input = keyboard.nextDouble();
  13. i++;
  14. result *= input;
  15. }
  16. result = (double) Math.pow(result, (double) 1 / years);
  17. return result;
  18. }

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

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

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

展开查看全部

相关问题