哪些网站用天平做logo网站排名查询站长之家
目录
- 1 使用函数求最大值
- 2 求最大值方法的重载
- 3 求和方法的重载
1 使用函数求最大值
使用函数求最大值:创建方法求两个数的最大值max2,随后再写一个求3个数的最大值的函数max3。
要求: 在max3这个函数中,调用max2函数,来实现3个数的最大值计算。
实现代码:
public class test2{public static int max2(int a,int b){int ret = (a>b)?a:b;return ret;}public static int max3(int a,int b,int c){int ret1 = max2(max2(a,b),c);return ret1;}public static void main(String[] args) {System.out.println(max2(1,2));System.out.println(max3(1,2,3));}
}
2 求最大值方法的重载
在同一个类中定义多个方法:要求不仅可以求2个整数的最大值,还可以求3个小数的最大值?(自己写和调库函数两种方法)
方法一:自己写实现函数
public class test2{public static int comp(int a,int b){if(a >= b){return a;}else{return b;}}public static double comp(double a,double b,double c){double result = (a > b)?a:b;double ret = (result > c)?result:c;return ret;}public static void main(String[] args) {System.out.println(comp(1,2));System.out.println(comp(1.0,2.0,3.0));}
}
方法二:调用库函数 Math.max(a,b)
public class test2{public static int comp(int a,int b){return Math.max(a,b);}public static double comp(double a,double b,double c){double m = Math.max(a,b);return Math.max(m,c);}public static void main(String[] args) {System.out.println(comp(1,2));System.out.println(comp(1.0,2.0,3.0));}
}
3 求和方法的重载
在同一个类中,分别定义求两个整数的方法 和 三个小数之和的方法。
实现代码:
public class test2{public static int add(int a,int b){return a+b;}public static double add(double a,double b,double c){return a+b+c;}public static void main(String[] args) {System.out.println(add(1,2));System.out.println(add(1.0,2.0,3.0));}
}