在 C++ 中使用巢狀的 if-else 語句

Jinku Hu 2023年10月12日
  1. 在 C++ 中使用單一的 if-else 語句來實現條件語句
  2. 使用巢狀的 if-else 語句在 C++ 中實現多條件程式控制流
在 C++ 中使用巢狀的 if-else 語句

本文將解釋幾種在 C++ 中如何使用巢狀 if-else 語句的方法。

在 C++ 中使用單一的 if-else 語句來實現條件語句

C++ 語言提供了兩種語句來實現條件執行。一個是 if 語句-根據條件分支控制流,另一個是 switch 語句,該語句對表示式進行求值以選擇可能的執行路徑之一。if 語句可以表示為單個條件,也可以構造為控制不同執行路徑的多步語句。請注意,當單個語句符合條件時,可以在不使用大括號 {} 的情況下編寫語句來區分塊範圍。

#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int main() {
  vector<int> array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  if (array[0] > 1) cout << "array[0] <= 1" << endl;

  if (array[0] > 1) {
    cout << "array[0] <= 1" << endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

使用巢狀的 if-else 語句在 C++ 中實現多條件程式控制流

或者,可以將巢狀的 if-else 語句彼此連結在一起,以實現複雜的條件控制流。請注意,缺少給定的 if-else 大括號表示該塊將無條件執行。當巢狀多個 if 語句並且並非所有 if 條件在同一級別具有相應的 else 塊時,後一種情況最有可能。為避免此類問題,應嘗試強制使用大括號樣式或使用某些特定於 IDE 的工具來檢測程式碼中的此類問題。

#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int main() {
  vector<int> array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

  if (array[4] > array[3]) {
    cout << "array[4] > array[3]" << endl;
    if (array[4] > array[5])
      cout << "array[4] > array[5]" << endl;
    else
      cout << "array[4] <= array[5]" << endl;
  }

  if (array[4] > array[3]) {
    cout << "array[4] > array[3]" << endl;
    if (array[4] > array[5])
      cout << "array[4] > array[5]" << endl;
    else if (array[4] > array[6])
      cout << "array[4] > array[6]" << endl;
    else if (array[4] < array[5])
      cout << "array[4] < array[5]" << endl;
    else
      cout << "array[4] == array[5]" << endl;
  }

  return EXIT_SUCCESS;
}

輸出:

array[4] > array[3]
array[4] <= array[5]
array[4] > array[3]
array[4] < array[5]
作者: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - C++ Statement