下面是是一個比較復雜的類。
定義一個四則運算計算器Caculator的接口和實現。
在main函數中,讓用戶輸入四則運算表達式,比如a+b,a-b。
最後,在控制台輸出結果。
用到的語法:接口、類的定義,實例方法,switch-case語句。
/
/ // main.m // switch-case // // Created by fansunion on 15/11/15. // Copyright (c) 2015年 demo. All rights reserved. // #import@interface Caculator : NSObject -(void)setValue:(double)value; -(double)getResult; -(void)add:(double)value; -(void)sub:(double)value; -(void)multiply:(double)value; -(void)divide:(double)value; @end @implementation Caculator { double value; } -(void)setValue:(double)v{ value=v; } -(void)add:(double)v{ value+=v; } -(void)sub:(double)v{ value-=v; } -(void)multiply:(double)v{ value*=v; } -(void)divide:(double)v{ value/= v; } -(double)getResult{ return value; } @end int main(int argc, const char * argv[]) { @autoreleasepool { double value = 0; double v=0; char operator; Caculator *caculator =[[Caculator alloc]init]; NSLog(@請輸入表達式!); scanf(%lf %c %lf,&value,&operator,&v); [caculator setValue:value]; switch(operator){ case '+': [caculator add:v]; break; case '-': [caculator sub:v]; break; case '*': [caculator multiply:v]; break; case '/': [caculator divide:v]; break; default: NSLog(@未知的操作符); break; } NSLog(@%.2f,[caculator getResult]); } return 0; }
加法,2015+2014=4029
2015-11-15 17:23:13.722 switch-case[1684:89106] 請輸入表達式!
2015+2014
2015-11-15 17:23:21.586 switch-case[1684:89106] 4029.00
Program ended with exit code: 0
減法,2015-2020=-5
2015-11-15 17:23:44.579 switch-case[1688:89497] 請輸入表達式!
2015-2020
2015-11-15 17:23:55.500 switch-case[1688:89497] -5.00
Program ended with exit code: 0
乘法,2015*10=20150
2015-11-15 17:24:35.764 switch-case[1692:89985] 請輸入表達式!
2015*10
2015-11-15 17:24:45.414 switch-case[1692:89985] 20150.00
Program ended with exit code: 0
除法,2015/10=201.5
2015-11-15 17:24:58.379 switch-case[1696:90264] 請輸入表達式!
2015/10
2015-11-15 17:25:10.669 switch-case[1696:90264] 201.50
Program ended with exit code: 0
學習這個例子,感覺瞬間回到了2008年上半學年,大一上學期~