我正在研究 iPhone 计算器教程,但遇到了数字显示问题。
计算器屏幕在第一个操作数旁边“打印”第二个输入的操作数(数字),导致一些错误的计算,因为 currentNumber 输入了这个字符串。
我怎样才能让数字甚至运算符(+、-、*、/)全部显示出来并仍然正确执行计算?
- (IBAction)pressedDecimal:(id)sender {
calculatorScreen.text = [calculatorScreen.text stringByAppendingString:@"."];
}
- (IBAction)pressedDigit:(id)sender {
calculatorScreen.text = [calculatorScreen.text stringByAppendingFormat:@"%d", [sender tag]];
currentNumber = [calculatorScreen.text floatValue];
}
- (IBAction) pressedOperation: (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;
}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:@"%g", result];
if ([sender tag] == 0) result = 0;
currentOperation = [sender tag];
}
好的,这是一个完全输入的字符串 1.11+2.22 - 注意它把它们放在一起..
这是完成的计算,这是错误的..id 喜欢让字符串显示运算符 - 我应该使用 NSRange 来解决小数问题吗?