2013-06-19 113 views
1
#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    int i = 0; 
    while (i < 11) 
     cout << i << '\n'; 
     i++; 
} 

爲什麼此代碼重複輸出0而不是每次向我添加1?C++ while循環添加的問題

+5

C++是不是Python的:) – dasblinkenlight

+0

{所有關於括號} – ST3

回答

6

把你的陳述放在花括號裏{。否則,您只能在循環中執行輸出語句,並且i的增量將在循環之外發生。

+1

由於個人喜好,我總是用花括號,即使是單行循環機構,以避免像這樣:-) – Tom

+1

@湯姆我的錯誤第二個。 – Bathsheba

4

你的while循環沒有大括號。

它處理你的代碼爲:

while (i < 11) 
     cout << i << '\n'; 
    i++; 

,你真的想:

while (i < 11) 
    { 
     cout << i << '\n'; 
     i++; 
    } 
4

你需要寫:

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    int i = 0; 
    while (i < 11){ 
     cout << i << '\n'; 
     i++; 
    } 

} 

注意額外的支撐(i < 11)

出於興趣,它在形式上是最好使用for循環這裏:

int main() 
    { 
     for (int i = 0; i < 11; ++i){ 
      cout << i << '\n';     
     } 

    } 

注意如何我帶來i進入循環範圍,因此它不能在循環外部訪問;幫助程序穩定。所有happen到i(聲明,定義,終止條件和增量)都在同一行上;幫助可讀性。

0

C++中的循環只循環緊隨其後的語句,除非它們被放在代碼塊中。也就是說,你的代碼就相當於:

int main() 
{ 
    int i = 0; 
    while (i < 11) 
    { 
     cout << i << '\n'; 
    } 
    i++; 
} 

這這個代替:

int main() 
{ 
    int i = 0; 
    while (i < 11) 
    { 
     cout << i << '\n'; 
     i++; 
    } 
} 
1

在C++中你必須把一個單獨的語句到大括號與否的選擇。

但是,如果你在一個循環體多條語句,則必須使用括號:

while (i < 11) { 
    cout << i << '\n'; 
    i++; 
} 

C++是不敏感的空間例如像蟒,所以下面將工作,也:

while (i < 11) {cout << i << '\n';i++;} 

while (i < 11) 
{ 
    cout << i << '\n'; 
    i++; 
} 

while (i < 11) 



{ 
    cout << i << '\n'; 
    i++; 
} 
1

一個循環體可以是一個單一的語句:

while (i < 11) 
    cout << i << '\n'; 

或複合語句;也就是一組括號括起來的語句:

while (i < 11) { 
    cout << i << '\n'; 
    i++; 
} 

當你想要第二個時,你寫了第一個表單。與其他一些語言不同,縮進在C++中沒有意義,並且在使用{}包圍語句時,語句只被分組爲塊。

0
while (i < 11) 
    { 
     cout << i << '\n'; 
     i++; 
    } 
+2

但這個新的答案除了已經寫好的答案之外並沒有增加任何東西 – Bathsheba