C 语言逻辑与运算符

17 Mar 2025 | 4 分钟阅读

逻辑运算符通过连接两个或多个表达式或条件,对给定表达式执行逻辑运算。它可用于各种关系和条件表达式。该运算符基于布尔值来逻辑检查条件,如果条件为真,则返回 1。否则,返回 0 (False)。在 C 编程中,逻辑运算符分为三种类型,例如逻辑 AND (&&) 运算符、逻辑 OR (||) 运算符和逻辑 NOT (!) 运算符。在这里,我们学习逻辑 AND 运算符及其在 C 编程语言中的各种示例。

Logical AND Operator in C

逻辑 AND 运算符

逻辑 AND 运算符表示为“&&”双与号。它通过在表达式中组合来检查两个或多个操作数的条件,如果所有条件都为真,则逻辑 AND 运算符返回布尔值 true 或 1。否则,返回 false 或 0。

注意:如果两个值都非零,则条件将保持为真。否则,逻辑 AND (&&) 运算符返回 0 (false)。

语法

上述语法中有两个条件,condition1 和 condition2,以及双 (&&) 与号之间。如果两个条件都为真,则逻辑 AND 运算符返回布尔值 1 或 true。否则,返回 false。

逻辑 AND (&&) 运算符的真值表

ABA && B
111
100
010
000

示例 1:演示 C 语言中逻辑 AND 运算符的程序

输出

1
1
0
1

示例 2:使用逻辑 AND 运算符查找最大数字的程序

输出

Enter the first number: 20
Enter the second number: 10
Enter the third number: 50
50 is the largest number of all

示例 3:使用逻辑 AND (&&) 运算符检查用户是否是青少年的程序。

输出

Enter the age: 17
17 is a teenager age.

2nd execution:
Enter the age: 10
10 is not a teenager age.

示例 4:验证输入的数字是否在定义范围内的程序。

输出

Enter a number between 1 to 50: 19
The entered number is in the range 0 and 50.

2nd Run 
Enter a number between 1 to 50:
51
The entered number is in the range 50 and 100.

3rd execution:
Enter a number between 1 to 50:
0
Please enter the number is in the defined range.

示例 5:使用预定义的用户名和密码验证用户输入的用户名和密码是否正确的程序。

输出

Enter the username: system
Enter the password: admin@123

The user's credentials are correct.

2nd execution
Enter the username: system
Enter the password: admin@1234

The user's credentials are incorrect.