问题:求三个数中的最大值
上代码–
第一种 两两比较 每次取较大值 和第三个值比较 最终得到最大值
private static void maxIf2() {
int a = (int) (Math.random() * 100);
int b = (int) (Math.random() * 100);
int c = (int) (Math.random() * 100);
int max = a;
if (max < b) {
max = b;
}
if (max < c) {
max = c;
}
System.out.println(a + "," + b + "," + c + "中最大值是:" + max);
}
if 实现
假设 a最大给max
让max 和 b 比较 取较大值给max
然后再让 max和c 比较 再取 较大值给 max
至此 max 和所以数据 比较完毕 为最大值
去掉额外变量
private static void maxIf4() {
int a = (int) (Math.random() * 100);
int b = (int) (Math.random() * 100);
int c = (int) (Math.random() * 100);
System.out.print(a + "," + b + "," + c + "中最大值是:");
if (a < b) {
a = b;
}
if (a < c) {
a = c;
}
System.out.println(a);
}
if 没有max
该方式在a 不是最大值时 原来的值 将会被改变
第二种
private static void maxIf5() {
int a = (int) (Math.random() * 100);
int b = (int) (Math.random() * 100);
int c = (int) (Math.random() * 100);
System.out.print(a + "," + b + "," + c + "中最大值是:");
int max =0;
if (a >b && a>c) {
max=a;
} else if ( b > c && b >a) {
max = b;
}else {
max=c;
}
System.out.println(max);
}
if else if
这中方式需要 把条件写的很复杂
if else if 是只执行满足条件的那一个 其余的不执行
问题:根据分数判断优良中差
public class IfElse {
public static void main(String[] args) {
// >=90 优 80
int score=95;
if(score ){
System.out.println("差");
}else if(score ){
System.out.println("中");
}else if (score ){
System.out.println("良");
}else if(score>=90){ //该方式 最后一个条件 可以不写 不满足前面 score=90
System.out.println("优秀");
}
//错误示例
if(score ){
System.out.println("差");
}else if(score >=60){
System.out.println("中");
}else if (score >=80){
System.out.println("良");
}else if(score >=90){
System.out.println("优秀");
}
}
}
if else 条件规律
在else 之后的if 是对上一条 if 相对立条件 的再细分
else if(score >=60){ System.out.println("中");}else if (score >=80){ System.out.println("良");}
这 score >80 和 上一个条件的对立条件= score
Original: https://www.cnblogs.com/acman-mr-lee/p/16212546.html
Author: ACMAN-Mr.Lee
Title: if elseif else 怎么用?
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/586554/
转载文章受原作者版权保护。转载请注明原作者出处!