[英]Getting largest and second largest number in a sequence
Help me understand the last portion of this code that aims to print the largest and second largest number in a sequence. 帮助我理解此代码的最后一部分,该部分旨在按顺序打印最大和第二大数字。 What I am not fully understanding is, what is the need for the
else if
statement? 我不完全了解的是,
else if
语句有什么需要? with the code: 与代码:
if (input > largest) {
secondLargest = largest;
largest = input;
should that not do the job proper? 那应该做得不好吗? it checks if input is greater than the largest number, sets the second Largest to the previous largest number.
它检查输入是否大于最大数字,将第二个“最大”设置为前一个最大数字。 and update the new largest number with the one user inputed.
并在输入一个用户的情况下更新新的最大号码。
So what exactly is the purpose of this line of code then? 那么,这行代码的确切目的是什么? and any reason the integers
largest
and secondLargest
is set to -1
and not just 0
, has it to do with the sentinel
that breaks the program is set to 0
? 并且任何将integer
largest
和secondLargest
整数设置为-1
而不是0
是否与破坏程序的sentinel
设置为0
?
} else if (input > secondLargest) {
secondLargest = input;
. 。
int largest = -1;
int secondLargest = -1;
while (true) {
int input = readInt(" ? ");
if (input == SENTINEL) break;
if (input > largest) {
secondLargest = largest;
largest = input;
} else if (input > secondLargest) {
secondLargest = input;
}
Try your program with the sequence 按顺序尝试程序
1 2 3 5 4
If you omit else if (input > secondLargest) { secondLargest = input; }
如果省略
else if (input > secondLargest) { secondLargest = input; }
else if (input > secondLargest) { secondLargest = input; }
then result will be largest=5 and secondLargest=3, that is incorrect. else if (input > secondLargest) { secondLargest = input; }
结果将是maximum = 5和secondLargest = 3,这是不正确的。
该else if
代码处理情况下, input
下降的当前值之间的largest
和secondLargest
。
该else if
部分是,在情况的input
比不大于largest
,但大于secondLargest
时, secondLargest
应该改变,即使largest
也不会。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.