使用三元運算子查詢三個數字中最小的數字的Java程式


要使用三元運算子找到三個給定數字中最小的數字,請建立一個臨時變數來儲存兩個數字之間第一次比較運算的結果。然後,在第一次運算的結果(即temp)和第三個數字之間執行第二次比較運算,以獲得最終結果。

讓我們透過一個例子來理解問題陳述:

示例場景

Input: nums = 20, 35, 10;
Output: res = 10

什麼是三元運算子?

Java 中,條件運算子也稱為三元運算子。此運算子包含三個運算元,用於評估布林表示式。該運算子的目標是確定應為變數分配哪個值。此運算子的語法如下所示:

variable x = (expression) ? value if true: value if false

示例 1

這是一個 Java 程式,它說明了如何使用三元運算子查詢三個數字中最小的數字。

public class SmallestOf3NumsUsingTernary {
   public static void main(String args[]) {
      int a, b, c, temp, result;
      a = 10;
      b = 20;
      c = 30;
      temp = a < b ? a:b;
      result = c < temp ? c:temp;
      System.out.println("Smallest number is:: " + result);
   }
}

輸出

Smallest number is:: 10

示例 2

這是另一個使用三元運算子查詢三個數字中最小的數字的示例。在這裡,我們將比較邏輯傳遞給使用者定義的函式。

public class SmallestOf3NumsUsingTernary {
   public static void main(String args[]) {
      int a = 100, b = 20, c = 35;
      int smallest = findSmallest(a, b, c);
      System.out.println("Smallest number is:: " + smallest);
   }

   // User-defined function to find the smallest of three numbers
   public static int findSmallest(int a, int b, int c) {
      int temp = a < b ? a : b;
      return c < temp ? c : temp;
   }
}

輸出

Smallest number is:: 20

更新於:2024年9月11日

1K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.