所以我参加Xcode Objective-C课程,我们必须制作一个计算器。一切都有效,除了我必须创建例外的部分,如果有人试图除以零。我不能为我的生活让它工作,我一直得到的是我的计算器上的INF消息。此外,他们希望它是一种@try @catch
方法,因此我的Google搜索引导我自己提出问题,因为我无法找到答案。这是我的完整代码。
#import "Calculator.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize numerator, denominator, total, operand, theNumber, lblText;
- (void)viewDidLoad {
[super viewDidLoad];
[self setNumerator:0];
[self setDenominator:0];
[self setOperand:PLUS];
[self setTotal:0.0];
[self setTheNumber:@""];
[self printNumber];
}
-(void)printNumber
{
[lblText setText:theNumber];
}
-(float)divideOp
{
float result=0;
@try {
if (self.denominator != 0) {
result = (self.numerator / self.denominator);
} else {
result = NAN;
}
} @catch (NSException *exception) {
// deal with the exception
NSLog(@"Can't divide by 0!");
}
return result;
}
-(IBAction)calculate:(id)sender
{
denominator = [theNumber integerValue];
if(operand == PLUS)
total = numerator + denominator;
else if(operand == MINUS)
total = numerator - denominator;
else if(operand == MULTIPLY)
total = numerator * denominator;
theNumber = [NSString stringWithFormat:@"%f",total];
[self printNumber];
numerator = 0;
denominator = 0;
total = 0.0;
}
-(void)saveNumerator
{
numerator = [theNumber integerValue];
theNumber = @"0";
[self printNumber];
}
-(IBAction)clearNum:(id)sender
{
theNumber = @"0";
[self printNumber];
}
-(IBAction)setPlus:(id)sender
{
[self saveNumerator];
operand = PLUS;
}
-(IBAction)setMinus:(id)sender
{
[self saveNumerator];
operand = MINUS;
}
-(IBAction)setMultiply:(id)sender
{
[self saveNumerator];
operand = MULTIPLY;
}
-(IBAction)setDivide:(id)sender
{
[self saveNumerator];
operand = DIVIDE;
}
-(IBAction)press9:(id)sender
{
theNumber = [theNumber stringByAppendingString:@"9"];
[self printNumber];
}
-(IBAction)press8:(id)sender
{
theNumber = [theNumber stringByAppendingString:@"8"];
[self printNumber];
}
-(IBAction)press7:(id)sender
{
theNumber = [theNumber stringByAppendingString:@"7"];
[self printNumber];
}
-(IBAction)press6:(id)sender
{
theNumber = [theNumber stringByAppendingString:@"6"];
[self printNumber];
}
-(IBAction)press5:(id)sender
{
theNumber = [theNumber stringByAppendingString:@"5"];
[self printNumber];
}
-(IBAction)press4:(id)sender
{
theNumber = [theNumber stringByAppendingString:@"4"];
[self printNumber];
}
-(IBAction)press3:(id)sender
{
theNumber = [theNumber stringByAppendingString:@"3"];
[self printNumber];
}
-(IBAction)press2:(id)sender
{
theNumber = [theNumber stringByAppendingString:@"2"];
[self printNumber];
}
-(IBAction)press1:(id)sender
{
theNumber = [theNumber stringByAppendingString:@"1"];
[self printNumber];
}
-(IBAction)press0:(id)sender
{
theNumber = [theNumber stringByAppendingString:@"0"];
[self printNumber];
}
@end
答案 0 :(得分:0)
而不是设置:
result = NAN;
当你除以零时,你应该
NSException *e = [NSException
exceptionWithName:@"Divide By Zero"
reason:@"Divide by Zero Exception"
userInfo:nil];
@throw e;
不要在divideOp
方法中捕获异常...在任何应该打印计算结果的例程中捕获它,并打印出尝试非法除以零操作。