如何找到变量集的最大值

2022-09-03 18:04:11

我想知道是否有人可以帮助我找到一组变量的最大值并将其分配给另一个变量。这是我的代码片段,可能有助于理解我在说什么。

// Ask for quarter values.
    System.out.println("What is the value of the first quarter?");
    firstQuarter = input.nextDouble();

    System.out.println("What is the value of the second quarter?");
    secondQuarter = input.nextDouble();

    System.out.println("What is the value of the third quarter?");
    thirdQuarter = input.nextDouble();

    System.out.println("What is the value of the fourth quarter?");
    fourthQuarter = input.nextDouble();

    //Tell client the maximum value/price of the stock during the year.     
    //maxStock = This is where I need help 
    System.out.println("The maximum price of a stock share in the year is: $" + maxStock + ".");

答案 1

在Java中,您可以使用Math.max如下所示:

double maxStock = Math.max( firstQuarter, Math.max( secondQuarter, Math.max( thirdQuarter, fourthQuarter ) ) );

不是最优雅的,但它会起作用。

或者,对于更可靠的解决方案,请定义以下函数:

private double findMax(double... vals) {
   double max = Double.NEGATIVE_INFINITY;

   for (double d : vals) {
      if (d > max) max = d;
   }

   return max;
}

然后,您可以通过以下方式调用它:

double maxStock = findMax(firstQuarter, secondQuarter, thirdQuarter, fourthQuarter);

答案 2

一种方法来统治它们

public static <T extends Comparable<T>> T max(T...values) {
    if (values.length <= 0)
        throw new IllegalArgumentException();

    T m = values[0];
    for (int i = 1; i < values.length; ++i) {
        if (values[i].compareTo(m) > 0)
            m = values[i];
    }

    return m;
}