掘根宝典之C语言if,switch,break,continue,逻辑运算符(||,&&,!),?:运算符

本文详细解释了C语言中if语句、else、elseif、switch语句以及逻辑运算符(&&、||、!)的用法,包括它们的语法、工作原理和示例,同时介绍了continue和break在控制循环流程中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

if语句

C语言中的if语句用于执行给定条件下的一部分代码。

if语句的语法如下:

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

在这里,condition是一个表达式,如果为真,则执行if语句块中的代码。如果条件为假,则跳过if语句块中的代码。

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

#include <stdio.h>

int main() {
    int num = 10;

    if (num > 0) {
        printf("The number is positive.\n");
    }

    return 0;
}

在这个示例中,如果变量num的值大于0,则打印出"The number is positive."。否则,什么也不做。

else语句

else语句用于在if语句的条件为假时执行特定的代码块。

else必须与if配对使用

以下是else语句的一般语法:

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

在这里,如果条件为真,则执行if语句块中的代码。如果条件为假,则执行else语句块中的代码。

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

#include <stdio.h>

int main() {
    int num = 5;

    if (num % 2 == 0) {
        printf("The number is even.\n");
    } else {
        printf("The number is odd.\n");
    }

    return 0;
}

在这个示例中,如果变量num能够被2整除,则打印出"The number is even."。否则,打印出"The number is odd."。

注意,else语句不需要条件,它只会在前面的if语句的条件为假时执行。

else if语句

else if语句可以用来在if语句的条件为假时检查多个条件,并根据这些条件执行特定的代码块。else if语句可以与if语句和else语句一起使用,以处理多个可能的情况。

以下是else if语句的一般语法:

if (condition1) {
    // code to be executed if condition1 is true
} else if (condition2) {
    // code to be executed if condition2 is true
} else if (condition3) {
    // code to be executed if condition3 is true
} else {
    // code to be executed if all conditions are false
}

在这里,首先判断condition1的值,如果为真,则执行相应的代码块。如果condition1为假,则继续判断condition2的值,以此类推。如果所有条件都为假,则执行else语句块中的代码。

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

#include <stdio.h>

int main() {
    int num = 75;

    if (num >= 90) {
        printf("Grade A\n");
    } else if (num >= 80) {
        printf("Grade B\n");
    } else if (num >= 70) {
        printf("Grade C\n");
    } else if (num >= 60) {
        printf("Grade D
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值