替换范围内的字符

时间:2014-05-25 07:34:43

标签: objective-c logic calculator

我正在尝试将值插入字符串中,但我遇到了麻烦。我正在开发一个计算器,需要在计算结果时更新方程式字符串。

基本上我有这样的方法:

while (there are still powers in equation)
    calculatefirstgen

这样的calculatefirstgen方法:

for(the length of the equation)
    go through and check for a ^
    get the number on the left
    get the number on the right
    evaluate them
    update the equation
    return

并对等式进行了相应的更新:

    //make a range for the numbers i just evaluated
    NSRange range = NSMakeRange(lhsNumber, (((rhsNumber)-lhsNumber)));
    //get the result
    NSNumber *res = [NSNumber numberWithDouble:result];
    //replace the numbers i have evaluated with the result
    [runningEq replaceCharactersInRange: range withString:[res stringValue]];

这种方法看起来很棒,只要我的方程中只有一种力量。然而,当我引入第二个幂(像5+5^2+5+5^2这样的等式)时,它第一次通过(评估到5+25+5+5^2),但不是第二次。当它在第一轮评估并在更新方程后退出计算方法时,while循环将强制它重新执行该方法。第二次通过该方法就像第一次一样,并假设方程仍然是5+5^2+5+5^2,而实际上方程是5+25+5+5^2

我不知道等式是如何或为何不更新。任何帮助将不胜感激。

==================================

APOLOGIES,我刚刚意识到在我的循环中我引用了我原来的等式,这就是为什么会出现这个问题的原因。幸运的是,输入它有很多帮助,所以谢谢大家!只是要表明你需要多么谨慎的循环!

0 个答案:

没有答案
相关问题