% Function Name: mathProblem % Inputs (2): - (char) The name of the file contain
ID: 3537837 • Letter: #
Question
% Function Name: mathProblem
% Inputs (2): - (char) The name of the file containing directions
% - (double) Starting number
% Outputs (1): - (double) Final number modified by the directions in the
% file
%
% Function Description:
% Write a function called "mathProblem" that takes in a file containing
% directions and applies those directions to the input number. An example
% of a file would be:
%
% Add 5
% Subtract 2
% Divide 1
% Multiply 5
%
% According to this file, if the original number had been 3, the final
% number would be 30.The only commands that can be asked are
% 'Add', 'Subtract', 'Multiply', or 'Divide'.
% Notes:
% - The only directions that will be asked are the four listed above
% - If the input file is empty, the function should return the
% original number
% - There will only be one space between in the direction and the
% number in the file
% Test Cases:
Math1 file reads
Add 5
Subtract 2
Divide 1
Multiply 5
Math2 file reads
Multiply 3
Subtract 1
Divide 4
Multiply 2.5
Divide 2
Add 9
Math 3 file is empty
% result1 = mathProblem('math1.txt',3);
% result1 --> 30
%
% result2 = mathProblem('math2.txt',2);
% result2 --> 10.5625
%
% result3 = mathProblem('math3.txt',9);
% result3 --> 9
Explanation / Answer
function[final]= mathProblem(filename,number)
[Operation,value]=textread(filename,'%s %f');
final=number;
for i=1: size(Operation,1)
if strcmpi(Operation(i),'Add')
final=final+value(i);
elseif strcmpi(Operation(i),'Subtract')
final=final-value(i);
elseif strcmpi(Operation(i),'Multiply')
final=final*value(i) ;
elseif strcmpi(Operation(i),'Divide')
final=final/value(i) ;
end
end
end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.