加法正常工作,但减法变为负数。我尝试了不同的可能逻辑,但找不到合适的逻辑。前两个输入以及减号按钮提供了正确的解决方案。当与第三个输入一起使用减法时,此解决方案不会按应有的方式发生。有 0-9 个按钮可以输入数字。一个加号按钮触发以下方法
-(IBAction)adding:(id)sender;
,一个减号按钮触发此方法。
-(IBAction)subtract:(id)sender;
一个用于触发主要功能的等号按钮
-(IBAction)equals:(id)sender;
将被添加到减法和主要等号方法下面是函数实现的代码,即.m文件。
int eq;
@implementation ViewController
@synthesize temp = _temp;
@synthesize inputField = _inputField;
@synthesize outputField = _outputField;
-(IBAction)adding:(id)sender
{
self.temp = self.input + self.output;
self.input = 0;
eq = 0;
}
-(IBAction)subtract:(id)sender
{
self.temp = self.input - self.output;
self.input = 0;
eq = 1;
}
-(IBAction)digits:(id)sender
{
UIButton *b = (UIButton *)sender;
self.input = self.input * 10 + b.tag;
[self showInput];
}
-(IBAction)clear:(id)sender
{
self.input = 0;
[self showInput];
self.output = 0;
[self showOutput];
}
-(IBAction)clearE:(id)sender
{
self.input = self.input * 0.1;
[self showInput];
}
-(IBAction)equals:(id)sender
{
if (eq == 0) {
self.output = self.temp + self.input;
self.temp = 3;
}
if (eq ==1)
{
self.output = self.temp - self.input;
self.temp = 3;
}
[self showOutput];
self.input = 0;
[self showInput];
}
-(void)showInput
{
self.inputField.text = [NSString stringWithFormat:@"%lld", self.input];
}
-(void)showOutput
{
self.outputField.text = [NSString stringWithFormat:@"%lld", self.output];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.inputField.text = [NSString stringWithFormat:@"%lld",self.input];
self.outputField.text= [NSString stringWithFormat:@"%lld", self.output];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
.h文件是这样的:
@interface ViewController : UIViewController
@property (nonatomic,readwrite,weak) IBOutlet UILabel *inputField;
@property (assign,readwrite,) unsigned long long input;
@property(assign,readwrite) unsigned long long temp;
@property (nonatomic,readwrite,weak) IBOutlet UILabel *outputField;
@property (assign,readwrite) unsigned long long output;
-(IBAction)digits:(id)sender;
-(IBAction)adding:(id)sender;
-(IBAction)subtract:(id)sender;
-(IBAction)clear:(id)sender;
-(IBAction)clearE:(id)sender;
-(IBAction)equals:(id)sender;
@end