一.函数实现目标
写一个Matlab函数 function ret = myeval(str)计算表达式str的值。
str是一个算术表达式,即两个正整数的加法,减法,乘法和除法。
例如,myeval(’ 12+23 ‘)将执行返回35,myeval(’ 23-12 ‘)将返回11,myeval(’ 12*11 ‘)将返回132,myeval(’ 12/4 ‘)将返回3。
二.额外要求
(1) 其中可以多一个空格表达式,应该忽略它。
例如,“12 + 23”等于“12 + 23”。
(2)不能使用Matlab函数eval或num2str等现有的函数。
三.整体思路
核心思想:依靠ASCII码解决
step1
:将输入的字符串转化成ASCII码
step2
:检测有无空格,并将除了空格之外的字符的ASCII码保存到 ls[]
step3
:迭代 ls[],将第一个数的各个位保存到num1[],当检测到操作符时,将其保存到operator[], 并且跳出循环。
step4
: 将第二个数的(ls[]中除了第一个数和操作符)各个位保存到num2[]
step5
: 根据num1和num2计算这两个数的真实值Number1, Number2
根据ASCII码表,我们可以知道字符0对应的ASCII码是48,所以将字符的ASCII码减去48即可得到各个位的真实值,然后再根据在哪一位,计算出两个数字的真实值。
step6
: 根据操作符operator[]判断是哪种运算并计算出结果rat
四.完整代码
function ret = myeval(str)
% MYEVAL: calculate the addition, subtraction, multiplication and division of two Numbers entered as a string
% The core idea is to use ASCII code to distinguish between two numeric and operator types
% Converts the input string to ASCII code
str = abs(char(str));
ls = [];
% The number of number of the ASCII code of the string except space and set it to 1 initially
lsEND = 1;
for i = str
% All but Spaces (32 for ASCII code) are added to ls
if i ~= 32
ls(lsEND)= i ;
lsEND = lsEND + 1;
end
end
num1 = [];
% The number of number of the first number and set it to 1 initially
num1END = 1;
operator = [];
for i = ls
% Store each digit of the first number in num1
if i < 48 || i > 57
% Save the ASCII code for the operator and jump out of the for-loop
operator(1) = i;
break
end
num1(num1END) = i;
num1END = num1END + 1;
end
% Calculate the true value of the first number
Number1 = 0;
for m = 1:(num1END - 1)
% The ASCII - 48 of the numeric character gets the true value of the number, and then multiplies the corresponding number of digits
Number1 = Number1 + (num1(m) - 48) * 10^(num1END - 1 - m);
end
num2 = [];
% The number of number of the second number and set it to 1 initially
num2END = 1;
for j = ls(num1END + 1) : ls(end)
% Store each digit of the second number in num2
num2(num2END) = j;
num2END = num2END + 1;
end
% Calculate the true value of the second number
Number2 = 0;
for n = 1:(num2END - 1)
% The ASCII - 48 of the numeric character gets the true value of the number, and then multiplies the corresponding number of digits
Number2 = Number2 + (num2(n) - 48) * 10^(num2END - 1 - n);
end
% According to the ASCII code of the operator, what operation is to be performed and operate
% '+': 43; '-': 45; '*': 42; '/': 47;
switch operator(1)
case 43
ret = Number1 + Number2;
case 45
ret = Number1 - Number2;
case 42
ret = Number1 * Number2;
case 47
ret = Number1 / Number2;
end
end