1. Concept of logical operations
Logical operation is to combine multiple judgments to form complex conditions
x是非负数 !x<0
收入在2000到3500元之间 s>=2000 && s<3500
温度低于-15度或高于35度 t<=-15||t>=35
y年是闰年 (y%4==0 && y%100!=0)||y%400==0
2. About logical data
1. The logical value uses the value 1 to represent true and the value 0 to represent false;
2. It can perform arithmetic operations with numeric data;
3. When the value is used as a logical value, non-zero is regarded as "true" and 0 is regarded as "false".
3. Logical operators and rules
Priority: logical not "!"> logical and "&&"> logical or "||"
下面的运算如何进行?
a>b && x>y <=> (a>b) && (x>y)
a==b || x==y <=> (a==b)||(x==y)
!a || a>b <=> (!a)||(a>b)
a = !b + c > 0 <=> a=(((!b)+c)>0)
4. Logic Operation Application
1. Conditions for judging leap years: ① Divisible by 4, but not divisible by 100. ②It can be divisible by 400.
(year%4==0 && year%100!=0) || year%400==0
2. Identify non-leap year conditions: add a "!"
!((year%4==0&&year%100!= 0)||year%400==0)
3. The value range of x in the piecewise function 2<= x <=6 is converted to the code format as x>=2 && x<=6
V. Extension: Logic Short Circuit
A && B: If A is false, the value of the expression must be false, and B will not be evaluated
#include <stdio.h>
main()
{
int a = 5, b = 6, c = 7, d = 8, m = 2, n = 2;
(m = a > b) && (n = c > d);
printf("%d\t%d", m, n);
}
运行结果:
0 2
A || B: If A is true, the expression value must be true, and B will not be evaluated
#include <stdio.h>
main()
{
int a = 5, b = 6, c = 7, d = 8, m = 2, n = 2;
(m = a < b) || (n = c > d);
printf("%d %d", m, n);
}
运行结果:
1 2