Java--求三个数最大值的五种方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Luojun13Class/article/details/82934901

文章目录

前言

求出最大值,简单的用三个数来展示出五种方法,需要用到的时候直接过来借鉴就好!

内容

1、if语句嵌套

    int a = 10; int b = 30; int c = 20;
    int max;
    if (a > b)  {
    	if (a > c) {
    		max = a;
    	} else {
    		max = c;
    	}
    } else {
    	if (b > c) {
    		max = b;
    	} else {
    		max = c;
    	}
    }
    System.out.println(max);

2、if语句

    int a = 10; int b = 30; int c = 20;
    int max;
    if (a > b) {
    	max = a;
    } else {
    	max = b;
    }
    if (max < c) {
	    max = c;
    } 
    System.out.println(max);

3、if语句(假定a最大,b,c与a比较,如果比a大,则赋值给max)

    int a = 10;int b = 30;int c = 20;
    int max = a
    if (b > max) {
    	max = b;
    }
    if (c > max) {
    	max = c;
    }
    System.out.println(max);

4、三元运算符

    int a = 10;int b = 30;int c = 20;
    int temp = (a > b) ? a : b;
    max = (temp > c) ? temp : c;
    	或者
    int max = ((a > b ? a : b) > c) ? (a > b ? a : b) : c;(建议不用这种)
    System.out.println(max);

5、if语句 + 逻辑运算符 &&(a,b,c三个数,如果不是a最大,或者b最大,就是c最大)

    int a = 10;int b = 30;int c = 20;
    int max;
    if (a > b && a > c) {
    	max = a;
    } else if (c > a && c > b) {
    	max = c;
    } else
    max = b;
    System.out.println(max);

总结

总结出五种求最大值的方法,以方便将来所需要的时候能给自己带来帮助,同时也加深一下自己对这方面的理解和印象!

end

谢谢您的阅读!

猜你喜欢

转载自blog.csdn.net/Luojun13Class/article/details/82934901