我最近看了一个计算器 iPhone 应用的教程。它可以工作,但是我遇到了不需要的小数位的问题,这意味着我的应用程序会在我的数字后面加上一个点,并且后面有 6 个 0。我查找了如何解决此问题并尝试了我所看到的,但是它仅在我输入第一个数字时才有效。当我单击乘法、除法、减法或加法按钮时,它们会重新出现,当它显示答案时,它包括也不需要小数。我的代码如下,请帮助我,谢谢!
视图控制器.h
//
// ViewController.h
// Simple Calculator
//
// Created by Michael on 2013-08-08.
// Copyright (c) 2013 com.company. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
float result;
IBOutlet UILabel *calculatorScreen;
int currentOperation;
float currentNumber;
BOOL userInTheMiddleOfEnteringDecimal;
}
-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;
@end
视图控制器.m
//
// ViewController.m
// Simple Calculator
//
// Created by Michael on 2013-08-08.
// Copyright (c) 2013 com.company. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(IBAction)buttonDigitPressed:(id)sender {
if (!userInTheMiddleOfEnteringDecimal)
{
currentNumber = currentNumber *10 + (float ) [sender tag];
calculatorScreen.text = [NSString stringWithFormat:@"%2d",(int)currentNumber];
}
else{
calculatorScreen.text= [calculatorScreen.text stringByAppendingString:[NSString stringWithFormat:@"%d",[sender tag]]];
currentNumber = [calculatorScreen.text floatValue];
}
}
-(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;
}
}
currentNumber = 0;
calculatorScreen.text = [NSString stringWithFormat:@"%2f",result];
if ([sender tag] == 0) result=0;
currentOperation = [sender tag];
userInTheMiddleOfEnteringDecimal = NO;
}
-(IBAction)cancelInput {
currentNumber = (int)(currentNumber/10);
calculatorScreen.text = [NSString stringWithFormat:@"%.2f",currentNumber];;
}
-(IBAction) cancelOperation {
currentNumber = 0;
calculatorScreen.text = @"0";
userInTheMiddleOfEnteringDecimal = NO;
}
- (IBAction)dotPressed{
if(!userInTheMiddleOfEnteringDecimal){
userInTheMiddleOfEnteringDecimal = YES;
calculatorScreen.text= [calculatorScreen.text stringByAppendingString:@"."];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
谢谢 :)