Java不使用条件语句和数组如何获取三个随机数的最值与次大值
解决方法
你要的第二大值可以通过三数总和减去最大值再减去最小值直接得到,该方案完全符合「不使用条件语句、不使用数组」的要求。
核心逻辑说明
对于任意三个整数,三者的总和是固定的,减去最大值和最小值后,剩下的结果自然就是处于中间的第二大值,不需要额外的判断逻辑。
修正后的完整代码
import java.text.DecimalFormat; // 注:你导入的Scanner、Random实际代码中未使用,可以删除 public class Main { public static void main(String[] args) { DecimalFormat dcf = new DecimalFormat("0.00"); int high = 100; int 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); int totnum = a + b + c; double NumAvr = totnum / 3.0; // 注意这里用3.0避免整数除法截断小数 int max = Math.max(a, Math.max(b, c)); int min = Math.min(a, Math.min(b, c)); int second = totnum - max - min; // 第二大值 System.out.println("生成的三个随机数是: "+a+", "+b+", "+c); System.out.println("===================================================="); System.out.println("最大值是: "+ max); System.out.println("第二大值是: "+ second); System.out.println("最小值是: "+ min); System.out.println("三个数的平均值是: "+dcf.format(NumAvr)+"%"); } }
额外优化提示
原代码中计算平均值用totnum / 3会触发整数除法,比如三个数和为4时得到的平均值是1而不是1.33,改成totnum / 3.0即可得到正确的小数结果。
内容的提问来源于stack exchange,提问作者user17402424
相关产品推荐
相关产品推荐

