您的位置:首页 > 移动开发 > Objective-C

IOS开发之路-Objective-C 代码块(Block)-block计算器的实现

2013-08-07 17:35 609 查看
OC中的Block 和C中的函数指针非常相似 , 运用Block可以很方便的处理一些东西 。比如计算器

输入两个值之后 , 要对值进行运算处理 。

如果传统方式的话 ,会很不利与维护和更新 . 而且不便于使用。

但是运用block 我们需要知道用户需要做什么运算 , 我们把运算的方法传进去就好了.

如果以后要添加新的功能或者改旧的功能的话 , 维护起来就会很方便了。

今天就用block 做了一个oc的计算器 , 结合了c中的控制台输入输出 。

点击运行效果后为:

2013-08-07 17:32:51.155 Block计算器[1161:303]
Block (代码段)
计算器
请输入两个数:98 20
请选择要进行什么运算(+ - * / %) :\

您选择的有误,请重新选择
+
98.00 + 20.00 = 118.00

代码如下:

#import <Foundation/Foundation.h>

// 声明代码段
float add ( float (^)(float  , float ),float ,  float  );  //  加法
float sub ( float (^)(float  , float ),float  , float  );  //  减法
float mul ( float (^)(float  , float ),float  , float  );  //  乘法
float divide  ( float (^)(float  , float ),float  , float  );  //  除法
int sur  ( int (^)(int  , int ),int  , int  );  //  求余

int main(int argc, const char * argv[])
{

@autoreleasepool {
float fristNumber = 0.0f;
float secondNumber =  0.0f;
char sel = '\0';
float value = 0.0f;
int k = 1;
float(^addBlock)( float , float ) = ^(float x  , float y){
return x + y;
};
float( ^subBlock)(float ,  float ) = ^(float x , float y){
return  x - y;
};
float( ^mulBlock)(float ,  float ) = ^(float x , float y){
return  x * y;
};
float ( ^divBlock)(float , float ) = ^( float x , float y ){
return  x / y;
};
int( ^surBlock)(int ,  int ) = ^( int x , int y) {
return  x % y;
};

NSLog(@"\nBlock (代码段) 计算器");
printf("请输入两个数:");
scanf("%f%f",&fristNumber , &secondNumber);
getchar();
printf("请选择要进行什么运算(+ - * / %%) :");
while ( k >= 1) {
scanf("%c",&sel);
getchar();
if ( sel == '+') {
value =  add(addBlock, fristNumber, secondNumber);
k = 0;
}
else if ( sel  == '-'  ) {
value = sub(subBlock, fristNumber, secondNumber);
}
else if (sel == '*') {
value = mul(mulBlock, fristNumber, secondNumber);
k= 0;
}
else if (sel  == '/') {
value = mul(divBlock, fristNumber, secondNumber);
k = 0 ;
}
else if (sel  == '%') {
value = (int)sur(surBlock, fristNumber, secondNumber);
k =0;
}
else
{
printf("\n您选择的有误,请重新选择\n");
sel = '\0';
k++;
}
}
printf(" %.2f %c %.2f = %.2f",fristNumber,sel,secondNumber,value);
}
return 0;
}

// 实现代码段
float add ( float (^add)(float  , float ),float x,  float y ) //  加法
{
float addNumber = add(x,y);
return addNumber;
}
float sub ( float (^sub)(float  , float ),float x , float y )   //  减法
{
float subNumber = sub( x , y );
return subNumber;
}
float mul ( float (^mul)(float  , float ),float x , float y )  //  乘法
{
float mulNumber = mul( x , y );
return mulNumber;
}
float divide  ( float (^divide)(float  , float ),float x , float y )  //  除法
{
float divNumber = divide( x , y );
return divNumber;
}
int sur  ( int (^sur)(int  , int ),int x , int y )  //  除法
{
float surNumber = sur( x , y );
return surNumber;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐