【问题标题】:Evaluate equation but ignore order of mathematical operations and parentheses计算方程但忽略数学运算和括号的顺序
【发布时间】:2015-02-23 17:55:35
【问题描述】:

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

示例 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

我的函数不会忽略从左到右的规则。我该如何纠正这个问题?

【问题讨论】:

  • 你得到的输出是什么?当您提出问题时,包含此信息很重要。一方面,您不会在现有代码中使用 ^ 运算符拆分字符串。

标签: string matlab math


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢!我忘了去掉括号。
【解决方案2】:

这是一种没有任何 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

【讨论】:

  • 不错!我想没关系,但在第一行你也可以使用regexprepregexprep(str,'[ ()]','')
  • @Benoit_11 差不多,不是吗?
  • 哦,其实我记得我们想让str 的长度保持不变,但这并不重要,哈哈,对此感到抱歉
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-05
  • 2016-04-26
  • 2018-10-09
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
相关资源
最近更新 更多