我正在尝试学习 iOS,并且正在关注斯坦福大学的视频,我正在尝试重新创建一个计算器示例。但由于某种原因,= 按钮不起作用或没有给出结果。我一步一步地练习,但根本不适合我。任何人都可以帮助我,我将非常感激。
//这是我的Calculator.h
#import <UIKit/UIKit.h>
#import "CalculatorBrain.h"
@interface ViewController : UIViewController {
IBOutlet UILabel *display;
CalculatorBrain *brain;
BOOL userIsInTheMiddleOfTypingANumber;
}
-(IBAction) digitPressed:(UIButton *) sender;
-(IBAction) operationPressed: (UIButton *) sender;
@end
<code>
//This is my Calculator.m
<pre>
#import "ViewController.h"
#import "CalculatorBrain.h"
@implementation ViewController
-(CalculatorBrain *) brain
{
if (!brain) brain = [[CalculatorBrain alloc] init];
return brain;
}
-(IBAction) digitPressed:(UIButton *) sender
{
NSString *digit = [[sender titleLabel]text];
if (userIsInTheMiddleOfTypingANumber)
{
[display setText:[[display text] stringByAppendingString:digit]];
}else{
[display setText:digit];
userIsInTheMiddleOfTypingANumber = YES;
}
}
-(IBAction) operationPressed: (UIButton *) sender
{
if (userIsInTheMiddleOfTypingANumber)
{
[[self brain] setOperand:[[display text] doubleValue]];
userIsInTheMiddleOfTypingANumber = NO;
}
NSString *operation = [[sender titleLabel] text];
double result = [[self brain] performOperation:operation];
[display setText:[NSString stringWithFormat:@"%g", result]];
}
@end
<code>
//This is my CalculatorBrain.h
<pre>
#import <Foundation/Foundation.h>
@interface CalculatorBrain : NSObject {
double operand;
NSString *waitingOperation;
double waitingOperand;
}
-(void)setOperand:(double)anOperand;
-(double)performOperation:(NSString *) operation;
@end
<code>
//This is my CalculatorBrain.m
<pre>
#import "CalculatorBrain.h"
@implementation CalculatorBrain
-(void)setOperand:(double)anOperand{
operand = anOperand;
}
-(void) performWaitingOperation{
if ([@"+" isEqual:waitingOperation])
{
operand = waitingOperand + operand;
}
else if ([@"*" isEqual:waitingOperation])
{
operand = waitingOperand - operand;
}
else if ([@"-" isEqual:waitingOperation])
{
operand = waitingOperand * operand;
}
else if([@"/" isEqual:waitingOperation])
{
if (operand)
{
operand = waitingOperand / operand;
}
}
}
-(double)performOperation:(NSString *) operation
{
if ([operation isEqual:@"sqrt"])
{
operand = sqrt(operand);
}
else if([@"*+/-=" isEqual:operation])
{
[self performWaitingOperation];
waitingOperation = operation;
waitingOperand = operand;
}
return operand;
}
@end
<code>