Objective-c-arithmetic-operators

提供:Dev Guides
移動先:案内検索

Objective-Cの算術演算子

次の表は、Objective-C言語でサポートされているすべての算術演算子を示しています。 変数 A が10を保持し、変数 B が20を保持すると仮定します-

Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A* B will give 200
/ Divides numerator by denominator B/A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator increases integer value by one A++ will give 11
 —  Decrement operator decreases integer value by one A-- will give 9

次の例を試して、Objective-Cプログラミング言語で使用できるすべての算術演算子を理解してください-

#import <Foundation/Foundation.h>

int main() {
   int a = 21;
   int b = 10;
   int c ;

   c = a + b;
   NSLog(@"Line 1 - Value of c is %d\n", c );
   c = a - b;
   NSLog(@"Line 2 - Value of c is %d\n", c );
   c = a * b;
   NSLog(@"Line 3 - Value of c is %d\n", c );
   c = a/b;
   NSLog(@"Line 4 - Value of c is %d\n", c );
   c = a % b;
   NSLog(@"Line 5 - Value of c is %d\n", c );
   c = a++;
   NSLog(@"Line 6 - Value of c is %d\n", c );
   c = a--;
   NSLog(@"Line 7 - Value of c is %d\n", c );
}

上記のプログラムをコンパイルして実行すると、次の結果が生成されます-

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