21xrx.com
2024-09-20 01:09:12 Friday
登录
文章检索 我的文章 写文章
C++逻辑运算符:AND、OR和NOT
2023-07-07 12:42:37 深夜i     --     --
C++语言 逻辑运算符 AND OR NOT

在C++编程中,逻辑运算符是非常重要的概念,它们是用于比较两个或多个条件的工具。C++中有三个常用的逻辑运算符:AND(&&)、OR(||)和NOT(!)。

AND运算符(&&): AND运算符表示只有当所有条件都为真时,表达式才会返回真。比如,我们可以使用AND运算符来判断一个数字是否同时大于10和小于20,示例代码如下:


int num = 15;

if (num > 10 && num < 20)

 cout << "Number is between 10 and 20" << endl;

else

 cout << "Number is not between 10 and 20" << endl;

输出为:" Number is between 10 and 20 "。

OR运算符(||): OR运算符表示只要有一个条件为真,表达式就会返回真。比如,我们可以使用OR运算符来判断一个数字是否小于10或者大于20,示例代码如下:


int num = 5;

if (num < 10 || num > 20)

 cout << "Number is less than 10 or greater than 20" << endl;

else

 cout << "Number is between 10 and 20" << endl;

输出为:" Number is less than 10 or greater than 20 "。

NOT运算符(!): NOT运算符表示取反,即如果一个条件为真,应用NOT运算符后它将返回假,反之亦然。比如,我们可以使用NOT运算符来判断一个数字是否不等于10,示例代码如下:


int num = 11;

if (!(num == 10))

 cout << "Number is not equal to 10" << endl;

else

 cout << "Number is equal to 10" << endl;

输出为:" Number is not equal to 10 "。

逻辑运算符在C++编程中非常常用,通过使用它们,我们可以准确地判断条件,从而编写出更加健壮的程序。但请注意,当使用逻辑运算符时一定要小心,因为逻辑运算符的使用可能会造成程序的严重逻辑错误。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复