「inputLabel」という名前のラベルに入力を記録し、「outputLabel」という名前の別のラベルに回答を出力する電卓を作成しています (グラフ電卓に似ています)。ユーザーが式の入力を終了すると、式は次の場所に格納されます。 NSString オブジェクトを作成し、NSPredicate クラスで解析し、NSExpression クラスで評価しました.私が持っているものは機能しますが、特定の操作については答えが正しくないことに気付きました.たとえば、ユーザーが「25/2」と入力した場合、電卓は 12 を返しますが、これは明らかに正しくありません。ただし、ユーザーが「25/2.0」または「25.0/2」と入力すると、電卓は 12.5 を返しますが、これは私が望むものです。浮動小数点の代わりに整数。この場合、「expressionValueWithObject」メソッドを変更してオペランドを浮動小数点数として解釈する方法はありますか?
Brain.m
-(float)performCalculation: (NSString *)operation
{
NSPredicate *parsed = [NSPredicate predicateWithFormat:[operation stringByAppendingString:@"=1.0"]];
NSExpression *inputExpressionParsed = [(NSComparisonPredicate *)parsed leftExpression];
NSNumber *result = [inputExpressionParsed expressionValueWithObject:inputExpressionParsed context:nil];
return [result floatValue];
}
ViewController.m
- (IBAction)equalsPressed:(id)sender
{
//self.inputLabel.text = [self.inputLabel.text stringByAppendingString:@".0"];
NSString *inputExpression = self.inputLabel.text;
self.inputLabel.text = [self.inputLabel.text stringByAppendingString:@"="];
float result = [self.brain performCalculation:inputExpression];
self.outputLabel.text = [NSString stringWithFormat:@"%g", result];
}