【发布时间】:2021-12-25 13:04:18
【问题描述】:
作为一名大学 IT 一年级学生,我有一个 Java 作业,我必须显示三个随机生成的数字,并按最高、第二高、最低的顺序排列它们。我们教授提出的挑战是不使用任何条件语句或数组。
代码如下:
import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
DecimalFormat dcf = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
Random rand = new Random();
int high, low, totnum;
double NumAvr;
high = 100;
low = 1;
int a = (int)(Math.random()*(high-low+1)+low);
int b = (int)(Math.random()*(high-low+1)+low);
int c = (int)(Math.random()*(high-low+1)+low);
totnum = a + b + c;
NumAvr = totnum / 3;
System.out.println("The random grades are: "+a+", "+b+", "+c);
System.out.println("====================================================");
System.out.println("The highest number is: "+ Math.max(a, Math.max(b, c)));
System.out.println("The second number is: "+ Math.max(b, c));
System.out.println("The lowest number is: "+ Math.min(a, Math.min(b, c)));
System.out.println("The average of three numbers is: "+dcf.format(NumAvr)+"%");
//MathClass.java
}
}
我面临的问题是我正在努力获得最高和最低的“中间”值。是否有任何“中间”变量让我在不使用任何条件语句或数组的情况下获得第二高?
【问题讨论】:
-
如果不考虑int溢出,把它们全部相加,然后减去max和min。
-
@samabcde 75 到 100 之间的三个值;最大总和为 300。远低于 int 溢出。
-
@ElliottFrisch,为了安全起见。