java - 如何解决在四个随机生成的数字中找到最小数字时偶尔出现的错误答案
问题描述
我为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
不正确的输出
解决方案
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);
推荐阅读
- exe - a.out 文件和 .elf 文件格式有什么区别
- microsoft-graph-api - MS Graph API - 预订业务 - 添加具有“管理员”角色的员工创建“externalGuest”
- javascript - 按钮加载问题(没有包)
- java - 如何从 maven 插件中的 java 代码中引用 pom 中的 artifactId?
- c# - 如何在字典中添加 3 个以上的项目
- c# - 我可以检查用户是否响应然后将布尔值更新为 true 吗?
- css - Vue动态绑定到类不起作用
- php - providing factory methods to other classes
- python - Python - 追加元组时数据框列不符合要求
- python - 达到限制后使条件保持不变