2015-10-15 58 views
0

你好,我目前正在努力解決這一點的代碼。我想我已經破解了它,但是我一直在努力的一點是如何檢測每一個我輸入的數字來表示它讀取每個數字的次數。我對C++入門(流程執行)練習感到困惑

int main() 
{ 
    int currentValue = 0, value = 0; 
    int count = 1; 


    if (cin >> currentValue) //Get first number to process from user 
    { 
     while (cin >> value) //Get subsequent numbers 
     { 
      if (value == currentValue) //If subsequent numbers are the first as the first number entered 
      { 
       ++count; //Add to count for how many there are 
      } 

      else //if not 
      { 
       cout << currentValue << " occurs " << count << " times" << endl; 

       currentValue = value; //Remember the new value 
       count = 1; //Reset counter 
      } 
     } 

     //Prints for the value in the file 
     cout << currentValue << " occurs " << count << " times" << endl; 
    } 

    return 0; 
} 

我不確定if語句和while語句是如何一起工作以及它們的關係是什麼的。發生什麼事是,if語句讀取第一個數字,然後while語句讀取後面的數字?

+2

學習如何使用調試器(單步,逐行)以便自己看到流程總是很好的。 – PaulMcKenzie

回答

0

這是你所說的。 if語句試圖讀入currentValue,而試圖讀入value。 if語句首先被執行,然後while被執行,當條件成立時。他們之間沒有依賴關係。