Homework problem: Write a Matlab function with prototype function ret = myeval(str) to evaluate the expression str. The str is an arithmetic expression, i.e., the plus, minus, multiplication, and division of two numbers. For example, myeval(‘12+23’) will return 35, myeval(’23-12’) will return 11, myeval(‘12*11’) will return 132, and myeval(‘12/4’) will return 3. Notice that there can be one more spaces in the expression, which should be neglected. For example, ’12 + 23’ is the same as ‘12+23’. To make your life easier, you don’t need to worry about invalid inputs of str. Notice that you cannot use the Matlab functions eval or num2str. Instead, you have to parse the expression by yourself and calculate the result accordingly.
function ret = myeval(str)
%输入计算的字符串,返回运算符类型与运算符位置
ASCII_list= abs(str);
len_str = length(ASCII_list);
flag = 0;
position = 0;
for i = 1:len_str
if ASCII_list(i) == 43
flag = 1;
position = i;
elseif ASCII_list(i) == 45
flag = 2;
position = i;
elseif ASCII_list(i) == 42
flag = 3;
position = i;
elseif ASCII_list(i) == 47
flag = 4;
position = i;
end
end
pos1 = 1;
number1 = [0, 0];
%检索第一个数字
for j = 1:(position-1)
if ASCII_list(j) ~= 32
number1(pos1) = (ASCII_list(j) - 48);
pos1 = pos1 + 1;
end
end
pos2 = 1;
number2 = [0, 0];
%检索第二个数字
for k = (position+1):len_str
if ASCII_list(k) ~= 32
number2(pos2) = (ASCII_list(k) - 48);
pos2 = pos2 + 1;
end
end
%计算被加数字
number_1 = 10*number1(1)+number1(2);
number_2 = 10*number2(1)+number2(2);
%运算
if flag == 1
ret = number_1 + number_2;
elseif flag == 2
ret = number_1 - number_2;
elseif flag == 3
ret = number_1 * number_2;
elseif flag == 4
ret = number_1 / number_2;
end
end