本文主要是介绍Matlab手动实现两位数加减乘除,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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_strif ASCII_list(i) == 43flag = 1;position = i;elseif ASCII_list(i) == 45flag = 2;position = i;elseif ASCII_list(i) == 42flag = 3;position = i;elseif ASCII_list(i) == 47flag = 4;position = i;end
endpos1 = 1;
number1 = [0, 0];
%检索第一个数字
for j = 1:(position-1)if ASCII_list(j) ~= 32number1(pos1) = (ASCII_list(j) - 48);pos1 = pos1 + 1;end
endpos2 = 1;
number2 = [0, 0];
%检索第二个数字
for k = (position+1):len_strif ASCII_list(k) ~= 32number2(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 == 1ret = number_1 + number_2;
elseif flag == 2ret = number_1 - number_2;
elseif flag == 3ret = number_1 * number_2;
elseif flag == 4ret = number_1 / number_2;
end
end
这篇关于Matlab手动实现两位数加减乘除的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!