現代 C++:精華篇/迴圈
外觀
在本章中,我們有一個計算器,它願意執行比你願意輸入的更多的計算。
#include <iostream>
#include <string>
int main()
{
std::string input;
float a, b;
char oper;
float result;
// The ultimate truism, this never stops being true.
while(true)
{
std::cout << "Enter two numbers and an operator (+ - * /).\nOr press Ctrl+C to exit.\n";
// Take input.
std::cin >> input;
// Parse it as a float.
a = std::stof(input);
// Take input.
std::cin >> input;
// Parse it as a float.
b = std::stof(input);
// Take input.
std::cin >> input;
// Get the first character.
oper = input[0];
switch (oper)
{
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
}
std::cout << a << " " << oper << " " << b << " = " << result << "\n";
}
}
這個程式將一直執行,直到你的終端停止執行它(因為你按下了 Ctrl+C 或單擊了 X)。這是因為while 迴圈,每次控制到達其底部時,都會跳回到頂部 - 如果其條件仍然為真,在本例中它將始終為真。
如果我們不在使用者可以輕鬆停止迴圈的上下文中,while(true) 將是一個非常糟糕的主意。你可以用任何布林表示式(如 a == b)或 bool 變數替換括號中的 true。
假設我們希望允許最多十次迭代(透過迴圈),而不是無限次。我們可以這樣做
int i = 0;
while(i < 10)
{
//...
i++;
}
這將正常工作。
i++ 與 i = i + 1 相同,並導致 i 比以前大 1。它也與 i += 1 相同。
但是 C++ 提供了一種更漂亮的寫法,即for 迴圈
for(int i = 0; i < 10; i++)
{
//...
}
在第一次迭代中,i 的值為 0。在最後一次迭代中,它的值為 9。它永遠不會(有效地)有 10 的值,因為,就像我們在上面的等效 while 迴圈中一樣
- 迭代執行;
- 然後
i遞增; - 然後檢查
i < 10,如果它為假,則退出迴圈。
儘管如此,迴圈確實運行了 10 次。
正在建設中
- while 迴圈
- 持續迴圈,直到其條件為假。
- 迭代
- 透過迴圈進行一次傳遞。此外,迴圈或“迭代”的動作。
- for 迴圈
- 比 while 迴圈更適合計數。