三种Java求最大值的方法

2025-05-29 0 29

普通方法:

?

1

2

3

4

5

6

7

8

9

10

11
public class Max {

public static void main(String[] args) {

double[] myList = {1.9, 2.9, 3.4, 3.5,10,11,15,100,-1,-4.5}; //定义一维数组

double num = myList[0]; //0为第一个数组下标

for (int i = 0; i < myList.length; i++) { //开始循环一维数组

if (myList[i] > num) { //循环判断数组元素

num = myList[i]; } //赋值给num,然后再次循环

}

System.out.println("最大值为" + num); //跳出循环,输出结果

}

}

三元运算符:

?

1

2

3

4

5

6

7

8

9

10
public class Max {

public static void main(String[] args) {

double[] myList = {1.9, 2.9, 3.4, 3.5,10,11,15,1,-1,-4.2}; //定义一维数组

double num = myList[0]; //0为第一个数组下标

for (int i = 0; i < myList.length; i++){ //开始循环一维数组

num=(myList[i] < num?num: myList[i]); //三元运算符,详情看注解

}

System.out.println("最大值为" + num); //跳出循环,输出结果

}

}

注解:三元运算符的语法是 条件 ? 结果1 : 结果2;优点代码简洁,缺点可读性差

例子:int a,b,c;

a=2;b=3;

c=a>b?100:200;

语意:如果a>b,c=100;a<b,c=200

一般函数/方法:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
public class Max {

double[] myList = {1.9, 2.9, 3.4, 100,3.5,10,11,12,13,-1};

double num = myList[0];

void getValue(){ //创建一般方法

for (int i = 0; i < myList.length; i++) {

num=(myList[i] < num?num: myList[i]);//三元运算符

}

System.out.println("最大值为" + num);

}

public static void main(String args[]){

Max max=new Max(); //创建对象

max.getValue(); //通过对象调用一般方法

}

}

注解:方法三需要用到面向对象的思想

原文链接:https://www.idaobin.com/archives/297.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 三种Java求最大值的方法 https://www.kuaiidc.com/112056.html

相关文章

发表评论
暂无评论