一千萬個為什麽

搜索

如何找到一組變量的最大值

我想知道是否有人能幫我找到一組變量的最大值並將它們賦值給另一個變量。這裏是我的代碼片段,可以幫助理解我在說什麽。

// 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 + ".");

最佳答案

一種方法來統治他們

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

轉載註明原文: 如何找到一組變量的最大值