简体   繁体   English

请帮我理解这段代码背后的逻辑

[英]Please help me understand the logic behind this code

I have been doing problems for while loop in c++ and i got stuck on this problem.我一直在为 C++ 中的 while 循环做问题,但我陷入了这个问题。 Googled the answer to see what i had to do but now i dont understand the logic behind it and why it works.用谷歌搜索答案,看看我必须做什么,但现在我不明白它背后的逻辑以及它为什么起作用。

Here is the problem:这是问题所在:

A sequence consists of natural numbers and ends with 0. Determine the value of the second largest element in the sequence, that is, the element that will be the largest if you remove the largest element from the sequence.序列由自然数组成,以 0 结尾。确定序列中第二大元素的值,即如果从序列中删除最大元素,则该元素将成为最大元素。

Examples-> Input 1: 4, 4, 2, 3, 0 Output 1: 4 ;示例-> 输入 1: 4, 4, 2, 3, 0 输出 1: 4 ; Input 2: 2 1 0 Output 2: 1输入 2:2 1 0 输出 2:1

This is the code:这是代码:

#include <iostream>
using namespace std;
int main() {
    int n, max, smax = 0;
    cin >> n;
    max = n;
    while (n != 0) {
        cin >> n;
        if (n > max) {
            smax = max;
            max = n;
        }
        else if (n > smax) {
            smax = n;
        }
    }
    cout << smax;
    return 0;
}

So, from my understanding max is n so the statement if n > max will never be True.所以,根据我的理解maxn所以如果n > max的语句永远不会为真。 Unless value for max resets with each loop and is 0, but then its always going to be true so there is no point for the second if statement.除非max值在每个循环中重置并且为 0,否则它总是为真,所以第二个 if 语句没有意义。

Im sure i dont understand how the while loop works and i would like for someone to clear it up for me.我确定我不明白 while 循环是如何工作的,我希望有人为我清理它。 Thanks in advance.提前致谢。

While loop repeats its body until the given condition become false. While 循环重复其主体,直到给定的条件变为假。 It's relatively easy to make an infinite while loop error in code, eg:在代码中产生无限 while 循环错误相对容易,例如:

int i = 0;
while (i<10){
cout<<"something\n";
}

Please remember to put some operation that will break the loop in the body.请记住在正文中放置一些会打破循环的操作。 This would work:这会起作用:

int i = 0;
while (i<10){
cout<<"something\n";
i++; //equivalent of i=i+1;
}

Try it yourself: https://www.onlinegdb.com/online_c++_compiler This should help to understand the concept.自己试试: https : //www.onlinegdb.com/online_c++_compiler这应该有助于理解这个概念。

Your code actually makes no sense to me.你的代码对我来说实际上毫无意义。 You type some numbers and it changes them until you type 0, when it stops.你输入一些数字,它会改变它们,直到你输入 0,当它停止时。 It doesn't even show you the maximum value you typed.它甚至不显示您输入的最大值。 I highly recommend to learn something more clear and useful in C++.我强烈建议在 C++ 中学习更清晰和有用的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM