#include <iostream>
#include <string>
using namespace std;
int main()
{
int i = 0;
while (i < 11)
cout << i << '\n';
i++;
}
爲什麼此代碼重複輸出0而不是每次向我添加1?C++ while循環添加的問題
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i = 0;
while (i < 11)
cout << i << '\n';
i++;
}
爲什麼此代碼重複輸出0而不是每次向我添加1?C++ while循環添加的問題
你的while循環沒有大括號。
它處理你的代碼爲:
while (i < 11)
cout << i << '\n';
i++;
,你真的想:
while (i < 11)
{
cout << i << '\n';
i++;
}
你需要寫:
#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(聲明,定義,終止條件和增量)都在同一行上;幫助可讀性。
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++;
}
}
在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++;
}
一個循環體可以是一個單一的語句:
while (i < 11)
cout << i << '\n';
或複合語句;也就是一組括號括起來的語句:
while (i < 11) {
cout << i << '\n';
i++;
}
當你想要第二個時,你寫了第一個表單。與其他一些語言不同,縮進在C++中沒有意義,並且在使用{}
包圍語句時,語句只被分組爲塊。
C++是不是Python的:) – dasblinkenlight
{所有關於括號} – ST3