例:
求a,b,c,三个数中的最大值并输出;
刚开始的想法比较简单:
设置一个max值,依次比较并交换最大值即可;
max=a;
if(max<=b){
max=b;
}
if(max<c)
{
max=c;
}
System.out.println(max);
又或者是三个变量借助中间值相互交换
int temp;
if(a>b){
temp=a;
a=b;
b=temp;
}//每一次if比较都让a是最小值;
if(a>c){
temp=c;
a=c;
c=temp;
}
if(b>c){
temp=b;
b=c;c=temp;
}//每一次if比较都让c是最大值;
System.out.println(c);
==================================================
上面的方法都可以实现要求,但是在我们学习运算符的时候,发现三目运算符与上面的if代码段有相同功能
max=a;
if(max<=b){
max=b;
}
就等价于
int max;
max=a>b?a:b;
所以,三个数求最大值两行代码就可以搞定
int a=0,b=3,c=5;
int max;
max=a>b?a:b;
max=max>c?max:c;
System.out.println(max);