尝试为+
,-
,*
和/
函数创建一个简单的计算器。
我创建了一个分段框来传递一个操作符和两个文本字段来收集值。
If
txtBox1.text = 5
and
txtBox2.text = 9
and
Operator = +
在xcode中,如何从这个(5+9
)获取我创建的字符串并运行数学并返回txtBoxAnswer.text
?
这就是我所拥有的:
NSString *theMath;
- (IBAction)operatorSelected:(id)sender {
NSArray *theOperatorInCode =[NSArray arrayWithObjects:@"+",@"-",@"*",@"/", nil];
theMath = theOperatorInCode[_theOperator.selectedSegmentIndex];
}
- (IBAction)pressTheEquals:(id)sender {
int first = [self.theFirstNumber.text floatValue];
int second = [self.theSecondNumber.text floatValue];
**NSString *answer = [NSString stringWithFormat: @"%d,%@,%d",first,theMath,second];**
}
尝试接受NSString Answer并将该字符串放入数学公式中。
答案 0 :(得分:2)
非常简单,确实!
NSString *string1 = txtBox1.text;
NSString *string2 = txtBox2.text;
int number1 = [string1 intValue];
int number2 = [string2 intValue];
if([Operator isEqualToString:@"+"]) {
int result = number1 + number2;
txtBoxResult.text = [NSString stringWithFormat:@"%d", result];
}