天天看点

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      

继续阅读