在C++条件语句

简介: 在C++条件语句

在C++中,条件语句用于基于特定条件执行不同的代码块。C++提供了几种条件语句,其中最常见的包括 if 语句、if-else 语句、switch 语句以及 if-else if-else 语句。

1. if 语句

if 语句用于测试某个条件,如果条件为真(true),则执行相应的代码块。

cpp复制代码

 

if (condition) {

 

// code to be executed if the condition is true

 

}

2. if-else 语句

if-else 语句用于测试某个条件,如果条件为真,则执行 if 代码块;如果条件为假(false),则执行 else 代码块。

cpp复制代码

 

if (condition) {

 

// code to be executed if the condition is true

 

} else {

 

// code to be executed if the condition is false

 

}

3. if-else if-else 语句

if-else if-else 语句用于测试多个条件,并根据第一个为真的条件执行相应的代码块。如果所有条件都不为真,则执行 else 代码块(如果存在的话)。

cpp复制代码

 

if (condition1) {

 

// code to be executed if condition1 is true

 

} else if (condition2) {

 

// code to be executed if condition1 is false and condition2 is true

 

} else {

 

// code to be executed if both condition1 and condition2 are false

 

}

4. switch 语句

switch 语句用于基于变量的不同值来执行不同的代码块。它通常用于多选择的情况。

cpp复制代码

 

switch (variable) {

 

case value1:

 

// code to be executed if variable is equal to value1

 

break;

 

case value2:

 

// code to be executed if variable is equal to value2

 

break;

 

// ... more cases ...

 

default:

 

// code to be executed if none of the values match

 

}

switch 语句中,break 关键字用于终止 switch 语句的执行,并从该点跳出。如果没有 break,控制流将继续执行到下一个 case,这通常是不期望的,称为 "fall through"。

示例

下面是一个简单的 if-else if-else 语句的示例:

cpp复制代码

 

#include <iostream> 

 

 

 

int main() {

 

int score = 85;

 

 

 

if (score >= 90) {

 

std::cout << "Excellent!\n";

 

} else if (score >= 75) {

 

std::cout << "Good!\n";

 

} else if (score >= 50) {

 

std::cout << "Average.\n";

 

} else {

 

std::cout << "Poor.\n";

 

}

 

 

 

return 0;

 

}

在这个示例中,根据 score 变量的值,程序会输出不同的评级。如果 score 大于或等于 90,输出 "Excellent!";如果 score 在 75 到 89 之间,输出 "Good!";如果 score 在 50 到 74 之间,输出 "Average.";否则输出 "Poor."。

 

相关文章
|
1月前
|
C++
在C++语言中条件语句的类型
在C++语言中条件语句的类型
22 0
|
1月前
|
程序员 C++
C++条件语句
C++条件语句
26 0
|
C++
C++菜鸟学习笔记系列(14)——条件语句
C++菜鸟学习笔记系列(14)——条件语句
104 0
|
C++
C++条件语句教程
C++条件语句教程
192 0
C++条件语句教程
C++程序设计基础(3)条件语句和循环语句
注:读《程序员面试笔记》笔记总结 1.知识点 1.1条件语句 (1)if……;(2)if……else……;(3)if……else if……;(4)switch(){case ():break;case():break;default:}。
1098 0
|
6天前
|
C++
C++一分钟之-类与对象初步
【6月更文挑战第20天】C++的类是对象的蓝图,封装数据和操作。对象是类的实例。关注访问权限、构造析构函数的使用,以及内存管理(深拷贝VS浅拷贝)。示例展示了如何创建和使用`Point`类对象。通过实践和理解原理,掌握面向对象编程基础。
32 2
C++一分钟之-类与对象初步
|
1天前
|
编译器 C++
C++练级之路——类和对象(中二)
C++练级之路——类和对象(中二)
11 5
|
1天前
|
存储 编译器 C++
C++练级之路——类和对象(上)
C++练级之路——类和对象(上)
10 3
|
2天前
|
存储 Java C#
C++语言模板类对原生指针的封装与模拟
C++|智能指针的智能性和指针性:模板类对原生指针的封装与模拟
|
1天前
|
编译器 C++
C++练级之路——类和对象(中)
C++练级之路——类和对象(中)
7 1