英文:
Finding the lowest and largest number in a nested loop
问题
int smallest = 0;
int largest = 0;
int num;
for (int row = 1; row <= 5; row++) {
System.out.println();
System.out.println("学生 #" + row + " 的成绩:");
num = (int)(Math.random() * 50) + 50;
double total = 0;
smallest = num;
for (int col = 0; col < 10; col++) {
num = (int)(Math.random() * 50) + 50;
System.out.print(num + ", ");
total += num * 1.0;
}
System.out.println();
double average = total / 10;
System.out.println("学生的平均成绩为:" + average);
if (num > largest) {
largest = num;
}
if (num < smallest) {
smallest = num;
}
}
System.out.println("最高分数为:" + largest);
System.out.println("最低分数为:" + smallest);
英文:
int smallest = 0;
int largest = 0;
int num;
for (int row=1; row<=5; row++)
{
System.out.println();
System.out.println("Grades for student #" + row);
num = (int)(Math.random()*50)+50;
double total = 0;
smallest = num;
for (int col = 0; col<10; col++)
{
num = (int)(Math.random()*50)+50;
System.out.print(num+ ", ");
total += num*1.0;
}
System.out.println();
double average = total/10;
System.out.println("Average for student is " +
average);
if (num > largest) {
largest = num;
}
if (num < smallest) {
smallest = num;
}
}
System.out.println("The largest score is:" + largest);
System.out.println("The smallest score is : " +
smallest);
Trying to figure print out the lowest and largest score for random numbers generated in a loop for 5 students. The code is printing out the wrong number for lowest score.
答案1
得分: 2
最小和最大数都被初始化为0。它们应该用第一个值进行初始化。
英文:
The smallest and largest number are initialized with 0. They should be initialized with the first value instead.
答案2
得分: 0
你应该将这部分放在嵌套循环内部。
if (num > largest) {
largest = num;
}
if (num < smallest) {
smallest = num;
}
否则它们只会比较每行最后一列的 num
。
英文:
You should put this part inside the nested loop.
if (num > largest) {
largest = num;
}
if (num < smallest) {
smallest = num;
}
Otherwise they are only comparing num
of the last column of each row.
答案3
得分: 0
以下是从循环中查找最大值和最小值的代码片段。您可以根据您的要求进行调整。
int minMax = 0;
int smallest = 0;
int largest = 0;
for (int i = 1; i <= totalNumbers; i++) {
System.out.print("数字 " + i + ": ");
int inputNumbers = console.nextInt();
if (inputNumbers > largest) {
largest = inputNumbers;
} else if (inputNumbers < smallest) {
smallest = inputNumbers;
}
}
System.out.println();
System.out.println("最小值 = " + smallest);
System.out.println("最大值 = " + largest);
英文:
below is a code snippet of finding the largest and smallest value from a loop.you may adjust it with your requirement.
int minMax = 0;
int smallest = 0;
int largest = 0;
for(int i = 1; i <= totalNumbers; i++){
System.out.print("Number " + i + ": ");
int inputNumbers = console.nextInt();
if(inputNumbers > largest){
largest = inputNumbers;
} else if (inputNumbers < smallest){
smallest = inputNumbers;
}
}
System.out.println();
System.out.println("Smallest = " + smallest);
System.out.println("Largest = " + largest);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论