C++

C++ 知识量:19 - 82 - 316

5.2 条件语句><

if语句- 5.2.1 -

在C++中,if语句用于根据特定条件执行代码。这是其基本形式:

if (condition)  
{  
    // code to be executed if the condition is true  
}

这里的condition是一个表达式,其结果为真(非零)或假(零)。如果condition为真,那么大括号中的代码将会被执行。如果为假,那么这部分代码将会被跳过。

例如:

int x = 10;  
if (x > 5)  
{  
    cout << "x is greater than 5";  
}

在这个例子中,x > 5是一个条件。因为x的值是10,这个条件为真,所以"x is greater than 5"将会被打印出来。

此外,if语句还有另外两种形式:if...else和switch。

if...else语句- 5.2.2 -

C++中的if...else语句是一种条件控制语句,用于根据条件执行不同的代码块。if...else语句的基本语法如下:

if (condition)  
{  
    // code to be executed if the condition is true  
}  
else  
{  
    // code to be executed if the condition is false  
}

其中,condition是一个布尔表达式,如果它的值为true,则执行if语句下面的代码块;如果它的值为false,则执行else语句下面的代码块。

例如,下面的代码演示了如何使用if...else语句来判断一个数是否为正数:

int num = 10;  
if (num > 0)  
{  
    std::cout << "The number is positive." << std::endl;  
}  
else  
{  
    std::cout << "The number is not positive." << std::endl;  
}

在这个例子中,条件表达式为num > 0,因为num的值是10,所以条件为true,程序将输出"The number is positive."。

switch语句- 5.2.3 -

C++中的switch语句是一种用于根据不同的情况执行不同代码块的流程控制语句。它根据表达式的值与case语句匹配,执行相应的代码块。

下面是一个使用switch语句的示例:

#include <iostream>  
  
int main() {  
    int num;  
    std::cout << "Enter a number: ";  
    std::cin >> num;  
  
    switch (num) {  
        case 1:  
            std::cout << "You entered 1." << std::endl;  
            break;  
        case 2:  
            std::cout << "You entered 2." << std::endl;  
            break;  
        case 3:  
            std::cout << "You entered 3." << std::endl;  
            break;  
        default:  
            std::cout << "You entered a number not 1, 2, or 3." << std::endl;  
    }  
  
    return 0;  
}

在这个示例中,用户被要求输入一个数字。然后,switch语句根据输入的数字执行不同的代码块。如果输入的数字是1,那么执行第一个case语句中的代码块,打印"You entered 1."。如果输入的数字是2,那么执行第二个case语句中的代码块,打印"You entered 2.",以此类推。如果输入的数字没有匹配任何case语句,那么执行default语句中的代码块,打印"You entered a number not 1, 2, or 3."。每个case语句后都有一个break语句,用于跳出switch语句。