我按照教程制作了一个iOS计算器,我现在想要添加一个小数位的按钮。这是我的代码
头文件:
#import <UIKit/UIKit.h>
@interface CalcViewController : UIViewController {
float result;
float selectedNumber;
int selectedOperation;
IBOutlet UILabel *calcScreen;
}
-(IBAction)numberPressed:(id)sender;
-(IBAction)operationPressed:(id)sender;
-(IBAction)clearNumber:(id)sender;
-(IBAction)clearOperation:(id)sender;
@end
这是我的实施文件
#import "CalcViewController.h"
@implementation CalcViewController
-(IBAction)numberPressed:(id)sender {
selectedNumber = selectedNumber * 10 + (float) [sender tag];
calcScreen.text = [NSString stringWithFormat:@"%2g", selectedNumber];
}
-(IBAction)operationPressed:(id)sender {
if (selectedOperation == 0) {
result = selectedNumber;
} else {
switch (selectedOperation) {
case 1:
result = result + selectedNumber;
break;
case 2:
result = result - selectedNumber;
break;
case 3:
result = result * selectedNumber;
break;
case 4:
result = result / selectedNumber;
break;
case 5:
selectedOperation = 0;
break;
}
}
selectedNumber = 0;
calcScreen.text = [NSString stringWithFormat:@"%2g", result];
if ([sender tag] == 0) result = 0;
selectedOperation = [sender tag];
}
-(IBAction)clearNumber:(id)sender {
selectedNumber = 0;
calcScreen.text = @"0";
}
-(IBAction)clearOperation:(id)sender {
selectedNumber = 0;
calcScreen.text = @"0";
selectedOperation = 0;
}
我在另一个帖子上看到有人建议使用该方法:
- (IBAction)Decimal:(id)sender
{
NSString *currentText = calcScreen.text;
if ([currentText rangeOfString:@"." options:NSBackwardsSearch].length == 0) {
calcScreen.text = [calcScreen.text stringByAppendingString:@"."];
}
然而,这似乎对我没有用。它确实会让我输入一个小数点,但是当输入第二个数字时,小数点将会丢失。任何人都可以建议我可以实现的方法来实现我的目标吗?
提前干杯!
答案 0 :(得分:0)
我的想法是:将数字作为文本保留在屏幕上,将其他数字和/或小数点添加为文本。在执行操作时,只将它转换为浮点数(我会自己使用double,btw)。建议的方法应该可以正常工作。
类似的东西:
-(IBAction)numberPressed:(id)sender {
calcScreen.text = [calcScreen.text stringByAppendingString:[sender tag]];
}
-(IBAction)operationPressed:(id)sender {
selectedNumber = [calcScreen.text floatValue];
...
}
答案 1 :(得分:0)
一个快速提示,而不是使用
int selectedOperation;...
以及稍后的代码
switch (selectedOperation) {
case 1:
result = result + selectedNumber;
break;
case 2:
result = result - selectedNumber;
...
尝试使用typedef enum
typedef enum {
OperationTypeAdd = 0,
OperationTypeSub,
...
} OperationType
并在switch
块
switch (operationType) {
case OperationTypeAdd:
result = result + selectedNumber;
break;
case operationTypeSub:
result = result - selectedNumber;
break;