跳轉到內容

現代 C++:精華部分/現在開始有意思了。

來自 Wikibooks,開放世界中的開放書籍

到目前為止,我們所有的程式都很直接:從頂部開始,逐行讀取,直到到達底部。現在情況發生了變化,因為這不是編寫程式的真正有用方式。有用的程式通常會重複一些東西,或者決定不做一些東西。本章將介紹如何在執行時選擇執行路徑。

程式碼

[編輯 | 編輯原始碼]
#include <iostream>
#include <string>

int main()
{
	std::string input;
	int a, b;
	int greater;
	// This one starts out with a value.
	bool canDecide = true;

	std::cout << "Enter two integers to compare.\n";

	// Take input.
	std::cin >> input;
	// Parse it as an int.
	a = std::stoi(input);
	
	// Take input.
	std::cin >> input;
	// Parse it as an int.
	b = std::stoi(input);
	
	// This is equality, and it might be true now and false later.
	if(a == b)
	{
		// = does not mean equality, which means we can do this.
		canDecide = false;
	}
	else if (a < b)
	{
		greater = b;
	}
	else
	{
		greater = a;
	}
	
	if(canDecide)
	{
		std::cout << greater << " is the greater number.\n";
	}
	else
	{
		std::cout << "The numbers are equal.";
	}
}

bool布林 的縮寫,表示是或否、真或假。在本例中,布林變數 "canDecide" 初始化為 true。基本上,程式假設它 "可以決定" 哪個數字更大,直到看到相反的證據。以這種方式覆蓋布林值非常有用。

== 是相等運算子;它確定兩個值是否相等,並返回真或假。注意:它不會改變任何值的的值。

任何看起來像 if(...){...} 的都是一個 if 語句a == b 是一個 表示式,它計算為布林值。表示式是一些可以解析為值的程式碼。if(a == b) 後的花括號包含如果 a 等於 b 則執行的程式碼。

else if 表示 "否則,如果...",並且只有在第一個 if 語句的 條件(布林值)為假時才會測試它。else 本身不會測試任何條件,而是在其鏈中的任何 if 語句都沒有執行時才會執行。

當以這種方式選擇一些邏輯進行執行時,"控制" 被認為 "流入" 邏輯。因此,if 語句被認為是 控制流 語句或 控制結構,它是一組包含一些其他構造,這些構造將在後面介紹。

  • 編寫一個計算器,提示使用者輸入兩個浮點數和一個運算子,然後列印結果。
bool
兩個可能值之一,truefalse。也稱為 條件
表示式
一些可以解析為值的程式碼。
if 語句
如果其條件為真則執行。語法:if(condition){ }
控制流
哪些程式碼執行,以及執行順序。
控制結構
修改控制流的語句。也稱為 控制流語句
現代 C++:精華部分
 ← 數字運算 現在開始有意思了。 切換方式 → 
華夏公益教科書