天天看點

C++條件語句教程

文章目錄

條件和 If 語句 if 語句 else 語句 else if 語句 三元運算符

C++ 支援數學中常見的邏輯條件:

  • 小于:a < b
  • 小于或等于:a <= b
  • 大于:a > b
  • 大于或等于:a >= b
  • 等于a == b
  • 不等于:a != b

C++ 有以下條件語句:

  • 使用if指定的代碼塊将被執行,如果一個指定的條件是真
  • 使用else指定的代碼塊将被執行,如果相同的條件為假
  • 使用else if指定一個新的條件測試,如果第一個條件為假
  • 使用switch指定的代碼許多替代塊被執行

使用該if語句指定在條件為 時要執行的 C++ 代碼塊為true。

注意 if是小寫字母。大寫字母(If 或 IF)将産生錯誤。

例如:

#include <iostream>
using namespace std;

int main() {
  if (20 > 18) {
    cout << "20大于18哦!";
  }  
  return 0;
}
      

示範:

C++條件語句教程

如果if語句為假,則執行else

#include <iostream>
using namespace std;

int main() {
  int time = 20;
  if (time < 18) {
    cout << "不錯.";
  } else {
    cout << "你真棒!";
  }
  return 0;
}
      
C++條件語句教程

解釋:20)大于 18,是以條件為false。是以,我們繼續處理else條件并在螢幕上列印“你真棒”。如果時間小于 18,程式将列印“不錯”。

如果if語句為假,則執行else if,else if也為假才執行else:

#include <iostream>
using namespace std;

int main() {
  int time = 22;
  if (time < 10) {
    cout << "川川菜鳥.";
  } else if (time < 23) {
    cout << "川川菜鳥我愛你.";
  } else {
    cout << "川川菜鳥真帥.";
  }
  return 0;
}
      
C++條件語句教程

有一個 if else 的簡寫,它被稱為三元運算符, 因為它由三個操作數組成。它可用于用一行替換多行代碼。它通常用于替換簡單的 if else 語句。

文法:

variable = (condition) ? expressionTrue : expressionFalse;      

而不是寫:

#include <iostream>
using namespace std;

int main() {
  int time = 20;
  if (time < 18) {
    cout << "小了";
  } else {
    cout << "大了.";
  }
  return 0;
}
      

你可以簡單地寫:

#include <iostream>
using namespace std;

int main() {
  int time = 20;
  string result = (time < 18) ? "小了." : "大了.";
  cout << result;
  return 0;
}
      
C++條件語句教程

劃重點:

string  result = (time < 18) ? "小了." : "大了.";      

如果time小于18,則執行小了,否則執行大了。就相當于一個if…else語句。

粉絲群:813269919      

繼續閱讀