【问题标题】:String to functional math equation字符串到函数数学方程
【发布时间】:2014-02-21 05:35:58
【问题描述】:

尝试为+-*/ 函数创建一个简单的计算器。

我创建了一个分段框来传递一个运算符和两个文本字段来收集值。

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 答案并将该字符串放入数学方程式中。

【问题讨论】:

  • 你试过什么?你在网上搜索过吗?
  • 大量搜索互联网。
  • 那么你得到了什么?您对 Wasif Hossain 的回答有什么问题。
  • Wasif 的回答对操作员进行了硬编码。即 if 语句来检查运算符。如果您看到我的 - 分段框有四个可用选项。通过选择一个,变量 theMath 已更改运算符。然后将其与从 txtbox1 和 txtbox2 中提取的值连接起来。

标签: objective-c parsing string-concatenation


【解决方案1】:

确实很简单!

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];
}

【讨论】:

  • 又好又简单 :-) +1 :-)
猜你喜欢
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 2013-12-27
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多