运算符类似于小学数学学的那些东西,这里就列举一下,不拘泥于运算细节,作为一个程序猿都应该懂得的基本知识,不理解的去网上搜搜。在实际工作中,好多同事不懂位运算,位运算很实用,用多了就会了,有助于写出高效的代码。
数值运算:+,-,*,/,%,++,--
位运算:&,|,~,<<,>>
赋值运算:=,+=,-=,*=,/=,%=,&=,|=,<<=,>>=
a+=b; 等价于 a=a+b; 其他的类推
逻辑运算:&&,||,!,==
下面是简单的代码:
//
// main.m
// HelloWorld
//
// Created by Moluth on 17/4/5.
// Copyright (c) 2017年 Moluth. All rights reserved.
//
//头文件。里面包含了好多东西,可以算是一个基本框架吧
#import <Foundation/Foundation.h>
//main函数,程序入口 argc 参数个数,argv 所有参数字符串类型
int main(int argc, const char * argv[]) {
//从名字上来看,这个代码块应该可以自动释放内存
@autoreleasepool {
int a=17,b=2,c=0;
//数值运算
c=a+b;//加
NSLog(@"a+b=%d\n",c);
c=a-b;//减
NSLog(@"a-b=%d\n",c);
c=a*b;//乘
NSLog(@"a*b=%d\n",c);
c=a/b;//除 整数的除法结果还是整数,但是如果a和b存在浮点型,结果是浮点型
NSLog(@"a/b=%d\n",c);
c=a%b;//取余 只能在整数运算中使用
NSLog(@"a%b=%d\n",c);
//位运算,只能在整数运算中使用
c=a&b;//按位与
NSLog(@"a&b=%d\n",c);
c=a|b;//按位或
NSLog(@"a|b=%d\n",c);
c=~a;//按位取反
NSLog(@"~a=%d\n",c);
c=a>>b;//右移
NSLog(@"a>>b=%d\n",c);
c=a<<b;//左移
NSLog(@"a<<b=%d\n",c);
/*输出:
2017-04-05 15:33:58.113 HelloWorld[1624:102952] a+b=19
2017-04-05 15:33:58.116 HelloWorld[1624:102952] a-b=15
2017-04-05 15:33:58.116 HelloWorld[1624:102952] a*b=34
2017-04-05 15:33:58.116 HelloWorld[1624:102952] a/b=8
2017-04-05 15:33:58.117 HelloWorld[1624:102952] ab=1
2017-04-05 15:33:58.117 HelloWorld[1624:102952] a&b=0
2017-04-05 15:33:58.117 HelloWorld[1624:102952] a|b=19
2017-04-05 15:33:58.117 HelloWorld[1624:102952] ~a=-18
2017-04-05 15:33:58.117 HelloWorld[1624:102952] a>>b=4
2017-04-05 15:33:58.117 HelloWorld[1624:102952] a<<b=68
*/
c=10;
c++;
c--;
c+=5;
c-=5;
c*=5;
c/=5;
c|=5;
c&=5;
c>>=2;
c<<=2;
bool ba=true,bb=false,bc;
bc=!ba;
bc=ba&&bb;
bc=ba||bb;
bc=ba==bb;
}
return 0;//返回值
}