1.题目一:定义一个方法,该方法能够找出两个小数中的较小值并返回。在主方法中调用方法进行测试。
提示:<1>. 根据方法的功能描述,方法的参数应该是两个小数。
<2>.要返回两个小数的较小值,所以返回值类型是小数。
public static void main(String[] args){
//4.在main方法中我们调用方法,我们用输出打印的方式
System.out.println(getMinDouble(23.5,24.9));
}
//1.定义一个方法,它的返回值类型是小数,有两个形参。
public static double getMinDouble(double x , double y){
//2.这里我们需要比较两个数的较小值所以我们用三元运算符
double min = x > y?x : y;
//3.返回较小值
return min;
}
注意:方法里的比较较小的值还可以用if的判断语句。
2.题目二:定义一个方法,该方法能够找出三个整数中的最大值并返回。在主方法中调用方法测试执行。
提示:<1>:根据题意,方法中需要使用三个整数,所以方法参数应该是三个整数类型。
<2>方法需要有返回值,返回值的类型也是整数类型。
public static void main(String[] args){
//3.利用打印方法来调用方法
System.out.println(getMax(34,56,99));
}
//1.定义一个求三个数最大值的方法,形参为三个整数
public static int getMax(int a, int b,int c){
//2.这里我们利用if判断语句去实现求三个数的最大值
//首先我们通过比较a和b的值谁大
if(b > a){
return b;
}else{
return a;
//b大
}else if(b > c){
return b;
}else{
return c;
}else if(a > c){
return a;
}return c;
//通过上面的比较b就是最大值,为了更直观的去看,就将b的值赋值给max
int max = b;
return max;
}
注意:上面的还可以用三元运算符来书写:代码如下
public static void main(String[] args) {
System.out.println(getMax(99,309,77));
}
public static int getMax(int a,int b,int c){
int temp =a > b ?a:b;
int max = temp > c ?temp : c;
return max;
}
