MATLAB: Help with if, else if & else statements

busbus farefarehomeworkif-statements

I am working on the following question for a class. Write a function called fare that computes the bus fare one must pay in a given city based on the distance travelled. Here is how the fare is calculated: the first mile is $2. Each additional mile up to a total trip distance of 10 miles is 25 cents. Each additional mile over 10 miles is 10 cents. Miles are rounded to the nearest integer other than the first mile which must be paid in full once a journey begins. Children 18 or younger and seniors 60 or older get a 20% discount. The inputs to the function are the distance of the journey and the age of the passenger in this order. Return the fare in dollars, e.g., 2.75 would be the result returned for a 4-mile trip with no discount.
So far I have written the following but when I run the debugger I keep getting messages about my ends not being in the correct location. I have fiddled with moving the code around with the if, else and else if statements, but I seem to be missing something.
function f = fare(dm,ay)
dm = round(dm);
if (dm <= 1)
f = 2;
else if (dm> 1 && dm >= 10)
f = 2 + (dm-1) * 0.25;
else if (m > 10)
f = 2 + ((dm-1) * 0.25) + ((dm-10)* 0.10);
if (ay <= 18 || ay >= 60)
p = f(.80);
else
p = f;
end

Best Answer

You are using else if as if it was elseif
That is,
if condition1
action1
else if condition2
action2
end
is not valid. Valid would be
if condition1
action1
else if condition2
action2
end
end
which is equivalent to
if condition1
action1
else
if condition2
action2
end
end
Also legal is
if condition1
action1
elseif condition2
action2
end
Notice there is only a single end
You are probably wondering what the difference is between them. Well suppose you had
r = rand;
if r <= 1/2
disp('first half')
else if r <= 3/4
disp('third quarter')
end
disp('another message')
end
Then when we space it better, we get
r = rand;
if r <= 1/2
disp('first half')
else
if r <= 3/4
disp('third quarter')
end
disp('another message')
end
and you can see that 'another message' sent out as long as r <= 1/2 is false, including if r <= 3/4 is ture. But if we had
r = rand;
if r <= 1/2
disp('first half')
elseif r <= 3/4
disp('third quarter')
end
disp('another message')
then "another message" is always sent out.
Related Question