使用三元運算子查詢三個數字中最小的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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP