一、算术运算符
算术运算符用于执行基本的数学运算,如加法、减法、乘法、除法和取模等。
示例代码:
c复制代码
|
#include <stdio.h> |
|
|
|
int main() { |
|
int a = 10; |
|
int b = 5; |
|
int sum = a + b; |
|
int difference = a - b; |
|
int product = a * b; |
|
int quotient = a / b; |
|
int remainder = a % b; |
|
|
|
printf("Sum: %d\n", sum); |
|
printf("Difference: %d\n", difference); |
|
printf("Product: %d\n", product); |
|
printf("Quotient: %d\n", quotient); |
|
printf("Remainder: %d\n", remainder); |
|
|
|
return 0; |
|
} |
二、关系运算符
关系运算符用于比较两个值,并返回一个布尔值(真或假)。
示例代码:
c复制代码
|
#include <stdio.h> |
|
|
|
int main() { |
|
int a = 10; |
|
int b = 5; |
|
|
|
if (a > b) { |
|
printf("a is greater than b\n"); |
|
} else if (a < b) { |
|
printf("a is less than b\n"); |
|
} else { |
|
printf("a is equal to b\n"); |
|
} |
|
|
|
return 0; |
|
} |
三、逻辑运算符
逻辑运算符用于组合多个条件,以返回单个布尔值。
示例代码:
c复制代码
|
#include <stdio.h> |
|
|
|
int main() { |
|
int a = 5; |
|
int b = 10; |
|
int c = 15; |
|
|
|
if ((a > b) && (b < c)) { |
|
printf("Both conditions are true\n"); |
|
} else { |
|
printf("At least one condition is false\n"); |
|
} |
|
|
|
return 0; |
|
} |
四、位运算符
位运算符直接对整数类型(通常是补码形式)的位进行操作。
示例代码:
c复制代码
|
#include <stdio.h> |
|
|
|
int main() { |
|
unsigned int a = 60; // 60 = 0011 1100 |
|
unsigned int b = 13; // 13 = 0000 1101 |
|
int c = 0; |
|
|
|
c = a & b; // 12 = 0000 1100 |
|
printf("Line 1 - Value of c is %d\n", c); |
|
|
|
c = a | b; // 61 = 0011 1101 |
|
printf("Line 2 - Value of c is %d\n", c); |
|
|
|
c = a ^ b; // 49 = 0011 0001 |
|
printf("Line 3 - Value of c is %d\n", c); |
|
|
|
c = ~a; // -61 = 1100 0011 in 2's complement form due to a signed int type |
|
printf("Line 4 - Value of c is %d\n", c); |
|
|
|
c = a << 2; // 240 = 1111 0000 |
|
printf("Line 5 - Value of c is %d\n", c); |
|
|
|
c = a >> 2; // 15 = 0000 1111 |
|
printf("Line 6 - Value of c is %d\n", c); |
|
|
|
return 0; |
|
} |
五、赋值运算符
赋值运算符用于给变量赋值。
示例代码:
|
#include <stdio.h> |
|
|
|
int main() { |
|
int a; |
|
a = 10; |
|
printf("Value of a: %d\n", a); |
|
return 0; |
|
} |