0

我为 iPad 的计算器应用程序编写了这段代码,但我找不到解决十进制数字的方法。例如,当我尝试解决:4.5 + 0.5 时,它只会给我 4 个答案。我知道这其中缺少一些东西。

感谢那些传入的回复。

提前干杯!

- (IBAction)equalsPressed {
    self.typingNumber = NO;
    self.secondNumber = [self.calculatorDisplay.text intValue];

    int result = 0;

    if ([self.operation isEqualToString:@"+"]) {
        result = self.firstNumber + self.secondNumber;
    }
    else if ([self.operation isEqualToString:@"-"]) {
        result = self.firstNumber - self.secondNumber;
    }
    else if ([self.operation isEqualToString:@"*"]) {
        result = self.firstNumber * self.secondNumber;
    }
    else if ([self.operation isEqualToString:@"/"]) {
        result = self.firstNumber / self.secondNumber;
   }
    self.calculatorDisplay.text = [NSString stringWithFormat:@"%2.d", result];

    self.displayLabel.text = self.calculatorDisplay.text;
}

- (IBAction) clearPressed: (id)sender {
    self.calculatorDisplay.text = @"";
    self.firstNumber = [self.calculatorDisplay.text intValue];
    self.operation = [sender currentTitle];
}

- (IBAction)backspaceButton: (id)sender {
    self.displayLabel.text = [self.displayLabel.text substringToIndex:self.displayLabel.text.length - 1];
}

- (IBAction)decimalPressed:(id)sender {
    NSString *currentText = self.displayLabel.text;
    if ([currentText rangeOfString:@"." options:NSBackwardsSearch].length == 0) {
        self.displayLabel.text = [self.displayLabel.text stringByAppendingString:@"."];
    }
}
4

2 回答 2

2

你写了:

int result = 0;
  1. 更改intdouble
  2. intValue更改to的所有用途doubleValue
  3. 将格式字符串从 更改@"%2.d"@"%2.f"
于 2013-06-11T03:27:07.517 回答
0

您已在此行声明 result 为整数:

int result = 0;

这导致值以某种方式四舍五入。我还会仔细检查您使用的其他值是否也是正确的类型。如果输入值也是ints,那么您将计算int(4.5) + int(0.5)which is which is 4 + 0which is just 4.

如果您将其更改为浮点数或双精度数(取决于您的需要),它应该会更好。像这样:

float result = 0;
于 2013-06-11T03:23:39.857 回答