簡體   English   中英

請幫我理解這段代碼背后的邏輯

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

我一直在為 C++ 中的 while 循環做問題,但我陷入了這個問題。 用谷歌搜索答案,看看我必須做什么,但現在我不明白它背后的邏輯以及它為什么起作用。

這是問題所在:

序列由自然數組成,以 0 結尾。確定序列中第二大元素的值,即如果從序列中刪除最大元素,則該元素將成為最大元素。

示例-> 輸入 1: 4, 4, 2, 3, 0 輸出 1: 4 ; 輸入 2:2 1 0 輸出 2:1

這是代碼:

#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;
}

所以,根據我的理解maxn所以如果n > max的語句永遠不會為真。 除非max值在每個循環中重置並且為 0,否則它總是為真,所以第二個 if 語句沒有意義。

我確定我不明白 while 循環是如何工作的,我希望有人為我清理它。 提前致謝。

While 循環重復其主體,直到給定的條件變為假。 在代碼中產生無限 while 循環錯誤相對容易,例如:

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

請記住在正文中放置一些會打破循環的操作。 這會起作用:

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

自己試試: https : //www.onlinegdb.com/online_c++_compiler這應該有助於理解這個概念。

你的代碼對我來說實際上毫無意義。 你輸入一些數字,它會改變它們,直到你輸入 0,當它停止時。 它甚至不顯示您輸入的最大值。 我強烈建議在 C++ 中學習更清晰和有用的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM