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_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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值