我创建了一个简单的计算器。一切都很好;但是,如果我除以零,我想显示一条错误消息。我知道如何做警报弹出窗口,但我不知道如何实现它,所以它在我除以零时出现。这是我的计算器代码:
- (IBAction)buttonOperationPressed:(id)sender {
if (currentOperation == 0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
result = result / currentNumber;
break;
case 5:
currentOperation = 0;
break;
default:
break;
}
}
currentNumber = 0;
CalcDisplay.text = [NSString stringWithFormat:@"%g",result];
if ([sender tag] == 0) result = 0;
currentOperation = [sender tag];
userInTheMiddleOfEnteringDecimal = NO;
答案 0 :(得分:4)
您可以在进行分割之前添加测试,例如改变:
case 4:
result = result / currentNumber;
break;
为:
case 4:
if (currentNumber == 0)
// ... do alert here ...
else
result = result / currentNumber;
break;
答案 1 :(得分:1)
- (IBAction)buttonOperationPressed:(id)sender {
if (currentOperation == 0) result = currentNumber;
else {
switch (currentOperation) {
case 1:
result = result + currentNumber;
break;
case 2:
result = result - currentNumber;
break;
case 3:
result = result * currentNumber;
break;
case 4:
if(currentNumber == 0){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}else{
result = result / currentNumber;
}
break;
case 5:
currentOperation = 0;
break;
default:
break;
}
}
currentNumber = 0;
CalcDisplay.text = [NSString stringWithFormat:@"%g",result];
if ([sender tag] == 0) result = 0;
currentOperation = [sender tag];
userInTheMiddleOfEnteringDecimal = NO;
请尝试使用此代码,我已复制粘贴您提供的代码并添加了一些必要的代码,我认为这些代码可以解决您的问题。
答案 2 :(得分:1)
您必须检查第二个分区操作数是否为零,如果是,则打印错误消息。不要忘记,你不能只将double
或某些东西与==
进行比较,你必须使用预设,如下所示:
case 4:
if(ABS(currentNumber) < 1e-12) // most probably its zero
// your message
return;