2 回答
TA贡献1821条经验 获得超6个赞
我会使用Math.min(int, int) and Math.max(int, int)和一长串调用。喜欢,
Scanner input = new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int d = input.nextInt();
int e = input.nextInt();
int min = Math.min(Math.min(Math.min(Math.min(a, b), c), d), e);
int max = Math.max(Math.max(Math.max(Math.max(a, b), c), d), e);
您的“交换代码”毫无意义。这是另一个实现
Scanner input = new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
int d = input.nextInt();
int e = input.nextInt();
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
min = (a < min) ? a : min;
min = (b < min) ? b : min;
min = (c < min) ? c : min;
min = (d < min) ? d : min;
min = (e < min) ? e : min;
max = (a > max) ? a : max;
max = (b > max) ? b : max;
max = (c > max) ? c : max;
max = (d > max) ? d : max;
max = (e > max) ? e : max;
TA贡献1831条经验 获得超9个赞
为什么不将 a,b,c,d,e 值存储在最内层循环中,并在交换代码后再次将其重新分配给变量?像这样,
public static void main(String args[]) {
for (int a=0 ;a<=1 ;a++ ){
for(int b=0 ;b<=1 ;b++ ){
for(int c=0 ;c<=1 ;c++ ){
for(int d=0 ;d<=1 ;d++ ){
for(int e=0 ; e<=1 ;e++ ){
// Store the variable values
int ap = a;
int bp = b;
int cp =c;
int dp = d;
int ep = e;
// Swapping logic for finding min and max
// Due to swapping, the values of a,b,c,d,e may change
if ( a < b){
int tmp = a;
a=b;
b=tmp;
}
if ( a < c){
int tmp = a;
a=c;
c=tmp;
}
if ( a < d){
int tmp = a;
a=d;
d=tmp;
}
if ( a < e){
int tmp = a;
a=e;
e=tmp;
}
if ( c < b){
int tmp = b;
b=c;
c=tmp;
}
if ( d < b){
int tmp = b;
b=d;
d=tmp;
}
if ( e < b){
int tmp = b;
b=e;
e=tmp;
}
System.out.print(a+""+b+""+c+""+d+""+e+" ");
System.out.println(b + " " + a);
// Reassign the variable values
a = ap;
b = bp;
c=cp;
d=dp;
e=ep;
}
}
}
}
}
}
添加回答
举报