计算方程但忽略数学运算和括号的顺序
Evaluate equation but ignore order of mathematical operations and parentheses
我正在尝试编写一个忽略数学运算和括号顺序的函数。该函数只是从左到右评估运算符。 (对于 +-*/^
)
示例 1:5 - 3 * 8^2
returns 256
。
示例 2:4 / 2 - 1^2 + (5*3)
returns 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 行和第 6 行将其更改为 +-*/^
。
你的第二个例子失败了,因为你没有告诉你的程序如何忽略 (
和 )
字符。您应该在输入 switch
语句之前去除它们。
curNum = strrep(curNum,'(','')
curNum = strrep(curNum,')','')
switch sign
...
这是一种没有任何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
我正在尝试编写一个忽略数学运算和括号顺序的函数。该函数只是从左到右评估运算符。 (对于 +-*/^
)
示例 1:5 - 3 * 8^2
returns 256
。
示例 2:4 / 2 - 1^2 + (5*3)
returns 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 行和第 6 行将其更改为 +-*/^
。
你的第二个例子失败了,因为你没有告诉你的程序如何忽略 (
和 )
字符。您应该在输入 switch
语句之前去除它们。
curNum = strrep(curNum,'(','')
curNum = strrep(curNum,')','')
switch sign
...
这是一种没有任何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