1. 主页
  2. 文档
  3. C语言教程
  4. C语言运算符
  5. C中的运算符和算术运算符简介

C中的运算符和算术运算符简介

 

运算符是任何编程语言的基础。因此,如果不使用运算符,C 语言的功能是不完整的。运算符允许我们对操作数执行不同类型的操作。在 C 中,运算符可以分为以下几类: 

  • 算术运算符s (+, -, *, /, %, post-increment, pre-increment, post-decrement, pre-decrement)
  • 关系运算符(==、!=、>、<、>= & <=) 逻辑运算符(&&、|| 和 !)
  • 位运算符(&、|、^、~、>> 和 <<)
  • 赋值运算符(=、+=、-=、*= 等)
  • 其他运算符(条件、逗号、sizeof、地址、重定向)

算术运算符:这些用于对操作数执行算术/数学运算。属于这一类的二元运算符是: 

  • 加:“+”操作符添加两个操作数。例如,x+y
  • 减:“ – ”操作减去两个操作数。例如,xy
  • 乘:“*”运营商乘两个操作数。例如,x*y
  • 除:“/”由第二运营商将第一操作数。例如,x/y
  • 模:“%”操作符返回时第一操作数被第二分割余数。例如,x%y
// C program to demonstrate
// working of binary arithmetic
// operators
#include <stdio.h>

int main()
{
int a = 10, b = 4, res;

// printing a and b
printf("a is %d and b is %d\n", a, b);

res = a + b; // addition
printf("a+b is %d\n", res);

res = a - b; // subtraction
printf("a-b is %d\n", res);

res = a * b; // multiplication
printf("a*b is %d\n", res);

res = a / b; // division
printf("a/b is %d\n", res);

res = a % b; // modulus
printf("a%%b is %d\n", res);

return 0;
}

输出: 

a is 10 and b is: 4
a+b is: 14
a-b is: 6
a*b is: 40
a/b is: 2
a%b is: 2

属于一元算术运算符类别的有: 

  • 增量:“++”操作符用于递增的整数的值。当放置在变量名之前(也称为预增量运算符),它的值会立即增加。例如,++x。 
    并且当它放在变量名之后(也称为后自增运算符)时,它的值会暂时保留到执行该语句之前,并在执行下一条语句之前更新。例如,x++
  • 减量:“ – – ”操作符用于递减的整数的值。当放置在变量名之前(也称为预减运算符),它的值会立即递减。例如,– – x。 
    并且当它放在变量名之后(也称为后减运算符)时,它的值会暂时保留,直到执行该语句,并在执行下一条语句之前更新。例如,x – –
// C program to demonstrate working
// of Unary arithmetic
// operators
#include <stdio.h>

int main()
{
int a = 10, b = 4, res;

// post-increment example:
// res is assigned 10 only, a is not updated yet
res = a++;
printf("a is %d and res is %d\n", a,
res); // a becomes 11 now

// post-decrement example:
// res is assigned 11 only, a is not updated yet
res = a--;
printf("a is %d and res is %d\n", a,
res); // a becomes 10 now

// pre-increment example:
// res is assigned 11 now since
// a is updated here itself
res = ++a;

// a and res have same values = 11
printf("a is %d and res is %d\n", a, res);

// pre-decrement example:
// res is assigned 10 only since a is updated here
// itself
res = --a;

// a and res have same values = 10
printf("a is %d and res is %d\n", a, res);

return 0;
}

输出: 

a is 11 and res is 10
a is 10 and res is 11
a is 11 and res is 11
a is 10 and res is 10

 

这篇文章对您有用吗? 1