how do I get this loop to run and get the cost for each of these?

clc
clear
format compact
disp('Stephen,Gaber')
disp('ENGR1181,A1')
disp('MAT-11')
disp('Problem 27 Shipping_1')
for k=1:3
g=1;
e=1;
o=1;
service=input('enter type of service(ground,express,or overnight, g, e, or o): ','s');
wt=input('enter weight in pounds: ');
oz=input('enter weight in ounces: ');
wt=wt+oz/16;
if service==g
if wt<.5
cost=.70+.06*oz;
elseif wt>.5 && wt<5
cost=1.18+.42*ceil(2*wt-1);
else
cost=4.96+.72*ceil(wt-5);
end
end
if service==e
if wt<.5
cost=2.40+.25*oz;
elseif wt>=.5 && wt<.5
cost=4.40+1.20*ceil(2*wt-1);
else
cost=15.20+1.80*ceil(wt-5);
end
elseif service==o
if wt<.5
cost=12.20*.80*oz;
elseif wt<5
cost=18.60+4.80*.5*wt;
else
cost=61.80+6.40*wt;
fprintf('The cost of the shipment is %3.2f dollars',cost)
end
end
end
When I run them, I'm only able to enter the weight in pounds and weight in ounces. What do I have to change so that I can find out the cost for three of them as well?

Answers (1)

Steve - look at your input request for the type of service
service=input('enter type of service(ground,express,or overnight, g, e, or o): ','s');
The code is requesting that the user type in a character corresponding to the service - so g for ground. This string or character input is saved to the service local variable which is (once initialized) of data type char.
The code that follows, to map the cost equation to the type of service tries to compare this character to a number
if service==g
or
if service==e
or
elseif service==o
All three return false because the comparison is between a character and a double. You should be using the string comparison function strcmpi. Try changing your code to
if strcmpi(service,'g')
% cost equation for ground service
elseif strcmpi(service,'e')
% cost equation for express service
elseif strcmpi(service,'o')
% cost equation for overnight service
else
fprintf('invalid service selection of %s!\n',service);
continue;
end
fprintf('The cost of the shipment is %3.2f dollars\n',cost);
Note the else statement that writes an error to the console and skips (via continue) to the next iteration of the for loop. The final line (from above) is just to write out the cost (for any of the three services) once it has been calculated. Note that you could experiment with the above and replace the if/elseif/elseif/else with a switch statement.

Tags

Asked:

on 11 Nov 2014

Answered:

on 12 Nov 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!