Objective-C 算术运算符

下表显示了 Objective-C 语言支持的所有算术运算符。假设变量 A 为 10,变量 B 为 20,则

运算符描述实例
+将两个操作数相加A + B = 30
-从第一个操作数中减去第二个操作数A - B = -10
*将两个操作数相乘A * B = 200
/将分子除以分母B / A = 2
%模算子和整数除法后的余数B % A = 0
++增量运算符将整数值增加一A++ = 11
减量运算符将整数值减少一A— = 9

实例

尝试以下实例以了解 Objective-C 编程语言中可用的所有算术运算符:

  1. #import <Foundation/Foundation.h>
  2. int main() {
  3. int a = 21;
  4. int b = 10;
  5. int c ;
  6. c = a + b;
  7. NSLog(@"Line 1 - Value of c is %d\n", c );
  8. c = a - b;
  9. NSLog(@"Line 2 - Value of c is %d\n", c );
  10. c = a * b;
  11. NSLog(@"Line 3 - Value of c is %d\n", c );
  12. c = a / b;
  13. NSLog(@"Line 4 - Value of c is %d\n", c );
  14. c = a % b;
  15. NSLog(@"Line 5 - Value of c is %d\n", c );
  16. c = a++;
  17. NSLog(@"Line 6 - Value of c is %d\n", c );
  18. c = a--;
  19. NSLog(@"Line 7 - Value of c is %d\n", c );
  20. }

结果如下:

  1. 2022-07-07 22:10:27.005 demo[25774] Line 1 - Value of c is 31
  2. 2022-07-07 22:10:27.005 demo[25774] Line 2 - Value of c is 11
  3. 2022-07-07 22:10:27.005 demo[25774] Line 3 - Value of c is 210
  4. 2022-07-07 22:10:27.005 demo[25774] Line 4 - Value of c is 2
  5. 2022-07-07 22:10:27.005 demo[25774] Line 5 - Value of c is 1
  6. 2022-07-07 22:10:27.005 demo[25774] Line 6 - Value of c is 21
  7. 2022-07-07 22:10:27.005 demo[25774] Line 7 - Value of c is 22

分类导航