我有一个简单的iOS / Objective C问题。我已经搜索了论坛并尝试了几种不同的方法,但我似乎无法解决这个问题,我对编码很新,所以我为此道歉可能看起来很傻。我试图建立一个简单的计算器,按钮从头开始,但我卡在小数部分。我使用switch语句通过按钮(id)发送者输入我的号码。你可以看到我注释掉的部分,这是我要用id标记10的地方,并写一些语句来实现浮点值的小数。
我还看了一个附加小数位的上一篇文章。我试图改变代码,但似乎我在这里遗漏了很多东西。
-(IBAction)decimalButton:(id)sender{
calculatorScreen.text = [calculatorScreen.text stringByAppendingFormat:@"."];
}
任何帮助/建议/示例代码都会非常有用,我再次对新手问题感到抱歉,我尽力学习基础知识。
#import "calcViewController.h"
@implementation calcViewController
-(IBAction)buttonDigitPressed:(id)sender { //ditits presed with sender tag
// switch ([sender tag]) {
// case 1:
// currentNumber = 1;
// break;
// case 2:
// currentNumber = 2;
// break;
// case 3:
// currentNumber = 3;
// break;
// case 4:
// currentNumber = 4;
// break;
// case 5:
// currentNumber = 5;
// break;
// case 6:
// currentNumber = 6;
// break;
// case 7:
// currentNumber = 7;
// break;
// case 8:
// currentNumber = 8;
// break;
// case 9:
// currentNumber = 9;
// break;
// case 10:
// //possibly implement decimal here
// break;
// }
currentNumber = (float)[sender tag]; //sets currentNumber to buttonPressed
calculatorScreen.text = [NSString stringWithFormat:@"%g",currentNumber];//displays button
}
-(IBAction)buttonOperationPressed:(id)sender {
//currentOperation is 0 by system default?
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;
currentNumber = result; //current number equals last resulting equation
calculatorScreen.text = [NSString stringWithFormat:@"%g",result]; //screen prints result
if ([sender tag] == 0) result = 0;
currentOperation = [sender tag];
}
答案 0 :(得分:0)
以下代码应正确更新屏幕。
-(IBAction)buttonDigitPressed:(id)sender { //ditits presed with sender tag
switch ([sender tag]) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
calculatorScreen.text = [calculatorScreen.text stringByAppendingFormat:@"%d", [sender tag]];
break;
case 10:
NSRange range = [calculatorScreen.text rangeOfString:@"."];
if ( range.location == NSNotFound ) {
calculatorScreen.text = [calculatorScreen.text stringByAppendingString:@"."];
}
break;
}
}
要在计算中使用此功能,请使用
float screenNumber = [calculatorScreen.text floatValue];