#include<stdio.h>
int main() {
int x = 10, y = 3;
float a = 15.5, b = 2.0;
int result1 = (x / y == a / b);
float result2 = (x % y) * (a / b);
printf("result1: %d\n", result1);
printf("result2: %.2f", result2);
return 0;
}
#include<stdio.h>
int main() {
int a = 5, b = 10, c = 15;
int result = a < b < c;
printf("result1: %d\n", result);
int d = 20, e = 25;
int result2 = (d > e) == (a < b);
printf("result2: %d", result2);
return 0;
}
运行结果:
result1: 1
result2: 0
解析:
- result1: 表达式 a < b < c 等价于 (a < b) < c
(5<10)=1 → 1<15=1 (真)
- result2: (d > e) → 20>25=0 (假)
(a < b) → 5<10=1 (真)
0 == 1 → 0 (假)
9
逻辑运算符进阶练习
高难度
嵌套逻辑与短路求值
分析以下程序,考虑短路求值和运算符优先级:
#include<stdio.h>
int main() {
int a = 0, b = 5, c = 10;
int result = !a || (b++ && c--) && (a = 5);
printf("result: %d\n", result);
printf("a: %d, b: %d, c: %d", a, b, c);
return 0;
}
#include<stdio.h>
int main() {
int x = 5, y = 10, z = 15;
int res1 = (x < y) && (y < z) || (z < x) && !(x == 5);
printf("res1: %d\n", res1);
int res2 = (x * 2 == y) || (y + 5 > z) && (z % x != 0);
printf("res2: %d\n", res2);
int a = 7, b = 12;
int res3 = (a & b) && (a | b);
printf("res3: %d", res3);
return 0;
}
#include<stdio.h>
int main() {
int x = 10, y = 20, z = 30;
z += x -= y *= 2;
printf("x: %d\n", x);
printf("y: %d\n", y);
printf("z: %d\n", z);
int a = 5, b = 5;
b += a *= b += 3;
printf("a: %d, b: %d", a, b);
return 0;
}
运行结果:
x: -30
y: 40
z: 0
a: 40, b: 48
解析:
- 第一组:赋值从右向左结合
y *= 2 → y = 40
x -= y → x = 10 - 40 = -30
z += x → z = 30 + (-30) = 0
- 第二组:
b += 3 → b = 8
a *= b → a = 5 * 8 = 40
b += a → b = 8 + 40 = 48
高难度
多重赋值与类型转换
以下程序涉及多重赋值和自动类型转换:
#include<stdio.h>
int main() {
int a, b, c;
float x, y, z;
a = b = c = 10.7;
x = y = z = 15;
printf("a=%d, b=%d, c=%d\n", a, b, c);
printf("x=%.1f, y=%.1f, z=%.1f\n", x, y, z);
char ch1, ch2;
int i1, i2;
ch1 = i1 = 300;
i2 = ch2 = 300;
printf("ch1=%d, i1=%d\n", ch1, i1);
printf("ch2=%d, i2=%d", ch2, i2);
return 0;
}
#include<stdio.h>
int calculate(int a, int b) {
return (a + b, a * b, a - b);
}
int main() {
int result1 = calculate(10, 5);
int result2 = (printf("Step12 "), printf("Step234 "), 100);
printf("\nresult1: %d\n", result1);
printf("result2: %d", result2);
return 0;
}