评估方程但忽略数学运算和括号的顺序

时间:2015-02-23 17:55:36

标签: string matlab math

我正在尝试编写一个忽略数学运算和括号的顺序的函数。该函数只是从左到右评估运算符。 (对于+-*/^

示例1:5 - 3 * 8^2返回256
示例2:4 / 2 - 1^2 + (5*3)返回18

这就是我的所作所为:

function out = calc(num)
    [curNum, num] = strtok(num, '+-*/^');
    out = str2num(curNum);
    while ~isempty(num)
        sign = num(1);
        [curNum, num] = strtok(num, '+-*/^');
        switch sign
        case '+'    
            out = out + str2num(curNum);
        case'-' 
            out = out - str2num(curNum);
        case '*'
            out = out.*str2num(curNum); 
        case '/'
            out = out./str2num(curNum);
        case '^'
            out = out.^str2num(curNum);
        end
    end
end

我的功能不会忽略从左到右的规则。我该如何纠正?

2 个答案:

答案 0 :(得分:4)

您的第一个示例失败,因为您正在使用+-*/分隔符拆分字符串,而您省略了^。您应该在第2行和第6行将其更改为+-*/^

您的第二个示例失败,因为您没有告诉您的程序如何忽略()个字符。您应该在输入switch语句之前删除它们。

curNum = strrep(curNum,'(','')
curNum = strrep(curNum,')','')
switch sign
...

答案 1 :(得分:4)

这是一种没有任何switch语句的方法。

str = '4 / 2 - 1^2 + (5*3)'

%// get rid of spaces and brackets
str(regexp(str,'[ ()]')) = [] 

%// get numbers
[numbers, operators] = regexp(str, '\d+', 'match','split')

%// get number of numbers
n = numel(numbers);

%// reorder string with numbers closing brackets and operators
newStr = [numbers; repmat({')'},1,n); operators(2:end)];

%// add opening brackets at the beginning
newStr = [repmat('(',1,n) newStr{:}]

%// evaluate
result = eval(newStr)

str =  
4/2-1^2+5*3

newStr =    
((((((4)/2)-1)^2)+5)*3)

result =    
    18