使用三元运算符查找三个数字中最小的数字的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