从2个阵列中获取最大数量 [英] Getting the largest number from each of the 2 arrays
本文介绍了从2个阵列中获取最大数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的Java自学中,我试图从2个数组中获取最大数字
我不知道为什么执行以下输出:
In my self study of Java, I'm trying to get the largest number from each of the 2 arrays
I don't know why the following output is being executed:
Largest: 3
Largest: 8
Largest: 9
Largest: 23
Largest: 33
Largest: 41
Largest: 51
正确的输出应该是:
The correct output should be:
Largest: 23
Largest: 51
以下代码如何获得最大数字?因为(getLargest1 [i]>最大)
等于 getLargest1 [i]> 0
,其中最大= 0
。
为什么要 largest = getLargest1 [i];
?
How could the following code get the largest number? Because (getLargest1[i] > largest)
is equal to getLargest1[i] > 0
, which largest = 0
.
Why should largest = getLargest1[i];
?
public class MyProgram
{
public void start()
{
int[] getLargest1 = {3, 8, 4, 9, 5, 5, 23, 14};
int[] getLargest2 = {33, 23, 41, 9, 17, 51, 23, 45};
getLargestFunc(getLargest1, getLargest2);
}
private void getLargestFunc(int[] getLargest1, int[] getLargest2)
{
int largest = 0;
for (int i = 0; i < getLargest1.length; i++)
{
if (getLargest1[i] > largest)
{
largest = getLargest1[i];
System.out.println("Largest: " + largest);
}
}
for (int i = 0; i < getLargest2.length; i++)
{
if (getLargest2[i] > largest)
{
largest = getLargest2[i];
System.out.println("Largest: " + largest);
}
}
}
}
推荐答案
你的ddea很好,那个代码工作正常。
if(getLargest1 [i]>最大)
是一个比较。您正在将下一个数字与尚未找到的最大数字进行比较。
largest = getLargest1 [i];
是你找到一个号码时的作业,这个号码比迄今为止找到的最大号码要大。
您应该将输出移到循环后面,这样您只能得到所需的输出:
Your ddea is good, that code is working correctly.
if (getLargest1[i] > largest)
is a comparison. You are comparing the next number to the yet found biggest number.
largest = getLargest1[i];
is an assignment when you've found a number, that is bigger than the so far found biggest number.
You should move the output behind the loops, so you'd get only the desired output:
public class MyProgram
{
public static void main(String[] args)
{
new MyProgram().start();
}
public void start()
{
int[] getLargest1 = {3, 8, 4, 9, 5, 5, 23, 14};
int[] getLargest2 = {33, 23, 41, 9, 17, 51, 23, 45};
getLargestFunc(getLargest1, getLargest2);
}
private void getLargestFunc(int[] getLargest1, int[] getLargest2)
{
int largest = 0;
for (int i = 0; i < getLargest1.length; i++)
{
if (getLargest1[i] > largest)
{
largest = getLargest1[i];
}
}
System.out.println("Largest: " + largest);
for (int i = 0; i < getLargest2.length; i++)
{
if (getLargest2[i] > largest)
{
largest = getLargest2[i];
}
}
System.out.println("Largest: " + largest);
}
}
这篇关于从2个阵列中获取最大数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文