0

我创建了一个简单的计算器。一切都很好;但是,如果我除以零,我想显示一条错误消息。我知道如何做警报弹出窗口,但我不知道如何实现它,所以当我除以零时它会出现。这是我的计算器代码的片段:

- (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;
4

3 回答 3

4

您可以在进行除法之前添加一个测试,例如更改:

        case 4:
            result = result / currentNumber;
            break;

到:

        case 4:
            if (currentNumber == 0)
                // ... do alert here ...
            else
                result = result / currentNumber;
            break;
于 2013-04-20T08:00:21.917 回答
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;

请尝试此代码,我已复制并粘贴了您提供的代码,并在其中添加了一些必要的行,我认为这可以解决您的问题。

于 2013-04-20T08:01:37.417 回答
1

您必须检查第二个除法操作数是否为零,如果是,则打印一条错误消息。不要忘记,你不能只比较double或与==,你必须使用 presicion,像这样:

case 4:
    if(ABS(currentNumber) < 1e-12) // most probably its zero
        // your message
        return;
于 2013-04-20T08:17:30.127 回答