I created some basic code for an intro to java class assignment to find the smallest number out of four randomly generated numbers from 0 to 10 inclusive using one (it has to be only one for the assignment) decision control structure, it works and gives correct answers, but occasionally it'll give the wrong answer (screenshots of incorrect answers will be attached since it may take a while to get an incorrect answer from the randomly generated numbers). I'm not sure what is causing the code to give the wrong answer on occasion.
//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
Incorrect Outputs
Aucun commentaire:
Enregistrer un commentaire