ViewController.m :
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutletUILabel *result; // label控件的连接,显示 result
@end
@implementation ViewController
- (IBAction)click0:(id)sender { // button控件,连接0,点击0触发的事件
if (Cal.op == '+' ||Cal.op == '-' || '*') { //触发+号...后的结果
Cal.opValue2 =Cal.opValue2*10 + 1; // 第二步操作的值;*10 为进位,0 代表 click0 操作;
self.result.text = [NSStringstringWithFormat:@"%f",Cal.opValue2]; //把第二步操作的值强制转换为字符串赋给label文本
}
else
{
Cal.opValue1 =Cal.opValue1*10 + 1;
self.result.text = [NSStringstringWithFormat:@"%f",Cal.opValue1];
}
}
........
- (IBAction)addclick:(id)sender {
Cal.op = '+'; //执行+
}
- (IBAction)subclick:(id)sender {
Cal.op = '-';
}
- (IBAction)subclick:(id)sender {
Cal.op = '*'; //执行+
}
- (IBAction)equalclick:(id)sender { // =
Cal.op = 0; //结果清零
Cal.opValue1 = 0;
Cal.opValue2 = 0;
float result = [Calwork]; // 计算结果
self.result.text = [NSStringstringWithFormat:@"%f",result];
}
- (IBAction)clean:(id)sender { //清除按钮
Cal.op = 0;
Cal.opValue1 = 0;
Cal.opValue2 = 0;
self.result.text = [NSStringstringWithFormat:@"%d",0]; //清除后显示 0
}
- (void)viewDidLoad {
[superviewDidLoad];
Cal =[[Calculatoralloc]init]; //对象初始化
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
ViewController.h :
{
Calculator *Cal; //创建对象
}
---------------------------@propertyfloat opValue1; //定义属性变量:前一步操作
@property float opValue2;
@property char op; //操作符
- (float)work; //声明 work方法
----------------
Calculator.h :
// 创建实例方法 work
- (float)work //设置返回值为 float
{
if(self.op=='+')
returnself.opValue1 +self.opValue2;
elseif(self.op=='-')
returnself.opValue1 -self.opValue2;
return 0; //必须有返回值
}
//- (float)work
//{
// if(self.op=='+')
// return self.opValue1 + self.opValue2;
// else (self.op=='-')
// return self.opValue1 - self.opValue2;
//}