首页 > 解决方案 > 如何解决在四个随机生成的数字中找到最小数字时偶尔出现的错误答案

问题描述

我为java类分配介绍创建了一些基本代码,以使用一个(它必须只有一个用于分配)决策控制结构从0到10(含)的四个随机生成的数字中找到最小的数字,它可以工作并给出正确的答案,但偶尔会给出错误答案(将附上错误答案的屏幕截图,因为从随机生成的数字中获得错误答案可能需要一段时间)。我不确定是什么导致代码有时给出错误的答案。

        //variables
        int num1, num2, num3, num4;

        //random
        num1 = (int) (Math.random() * 10) + 0;
        num2 = (int) (Math.random() * 10) + 0;
        num3 = (int) (Math.random() * 10) + 0;
        num4 = (int) (Math.random() * 10) + 0;

        //output
        System.out.println("The four random numbers are " +
                num1 + ", " + num2 + ", " + num3 + ", and " + num4);

        //smallest number decision
        if (num1 <= num2 && num1 <= num3 && num1 <= num4) {
            System.out.println("The smallest number is " + num1);

        } //if end

        else if (num2 <= num1 && num2 <= num3 && num1 <= num4) {
            System.out.println("The smallest number is " + num2);

        } //else if end

        else if (num3 <= num1 && num3 <= num2 && num3 <= num4) {
            System.out.println("The smallest number is " + num3);
        } //else if end

        else {
            System.out.println("The smallest number is " + num4);
        } //else end

不正确的输出

在此处输入图像描述

在此处输入图像描述

标签: javaif-statementrandom

解决方案


Problem (num1 < num4) is in the following line:

else if (num2 < num1 && num2 < num3 && num1 < num4) 

It should be:

else if (num2 < num1 && num2 < num3 && num2 < num4) 

Note: An easier way is as follows:

// variables
int num1, num2, num3, num4, min;

// random
num1 = (int) (Math.random() * 10) + 0;
num2 = (int) (Math.random() * 10) + 0;
num3 = (int) (Math.random() * 10) + 0;
num4 = (int) (Math.random() * 10) + 0;

// output
System.out.println("The four random numbers are " + num1 + ", " + num2 + ", " + num3 + ", and " + num4);

min = num1;
if (num2 < min) {
    min = num2;
}
if (num3 < min) {
    min = num3;
}
if (num4 < min) {
    min = num4;
}

System.out.println("The smallest number is " + min);

推荐阅读