我创建了一个简单的计算器。一切正常。但是,如果我除以零,我想显示一条错误消息。我知道如何执行警报弹出窗口,但是我不知道如何实现它,所以当我除以零时就会弹出警报。这是我的计算器代码片段:
- (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;
最佳答案
您必须检查第二个除法操作数是否为零,如果是,则输出错误消息。别忘了,您不能仅将double
或与==
进行比较,就必须使用presicion,如下所示:
case 4:
if(ABS(currentNumber) < 1e-12) // most probably its zero
// your message
return;
关于ios - 计算器除以零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16118080/