可能重复:
How do I change the number of decimal places iOS?
If using Xcode to make an iOS calculator, how would I add a decimal button?
我正在寻找一个关于如何制作(简单)iPhone计算器的iOS教程,该计算器至少可以执行以下操作:加,减,乘,除,并让用户输入小数点。我无法找到这样的教程,所以如果有人知道,请告诉我。我确实找到了一个你可以加,减,乘,除,但不能做小数点的地方。如果您可以告诉我如何让用户输入小数点,则无需进一步的教程。我现在使用的代码如下。
头文件中的:
#import <UIKit/UIKit.h>
@interface CalculatorViewController : UIViewController {
float result;
IBOutlet UILabel *calculatorScreen;
int currentOperation;
float currentNumber;
}
-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;
在主文件中:
#import "CalculatorViewController.h"
@implementation CalculatorViewController
-(IBAction)buttonDigitPressed:(id)sender {
currentNumber = currentNumber *10 + (float)[sender tag];
calculatorScreen.text = [NSString stringWithFormat:@"%.1f", currentNumber];
}
-(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:@"%.1f", result];
if ([sender tag] ==0) result=0;
currentOperation = [sender tag];
}
-(IBAction)cancelInput {
currentNumber =0;
calculatorScreen.text = @"0";
}
-(IBAction)cancelOperation {
currentNumber = 0;
calculatorScreen.text = @"0";
currentOperation = 0;
}
答案 0 :(得分:1)
这应该有效。简单直接。
更改了currentNumber以存储正在进行的计算的当前字符串值(Make this NSMutableString
),为小数点按钮添加了一个插座(buttonDecialPointPressed
)。
-(IBAction) buttonDigitPressed:(id)sender
{
currentNumber = [currentNumber appendFormat:@"%d"];
calculatorScreen.text = currentNumber;
}
- (IBAction) buttonDecialPointPressed:(id)sender
{
if(behindTheDecimal == YES)
return;
behindTheDecimal = YES;
currentNumber = [currentNumber appendString:@"."];
calculatorScreen.text = currentNumber;
}
-(IBAction)buttonOperationPressed:(id)sender
{
float number = [currentNumber floatValue];
switch (currentOperation)
{
case 0:
result = number;
break;
case 1:
result = result + number;
break;
case 2:
result = result - number;
break;
case 3:
result = result * number;
break;
case 4:
result = result / number;
break;
case 5:
currentOperation = 0;
break;
case 6:
break;
}
currentNumber = [currentNumber stringWithFormat:@"%f", result];
calculatorScreen.text = currentNumber;
// why is this needed, how is it used?
currentOperation = [sender tag];
}
-(IBAction)cancelInput
{
behindTheDecimal = NO;
currentNumber = @"0";
calculatorScreen.text = currentNumber;
}
-(IBAction)cancelOperation
{
behindTheDecimal = NO;
currentNumber = @"0";
calculatorScreen.text = currentNumber;
currentOperation = 0;
}