Problems with if function:

%I have to calculate the tax depending on the salary that the user inputs. For a salary less then 40726.00 %its 15%, from 40726.00 to 81452.00 its 22%, from 81452.00 to 126264.00 its 26% and then above 126264.00 %its 29%. This is the code I wrote:
Salaire1 = 40726.00;
Salaire2 = 81452.00;
Salaire3 = 126264.00;
y = input('Enter your salary:\n');
if (y<=Salaire1)
y=(y*15)/100
elseif (y>Salaire1 && y<=Salaire2)
y=((y-40726.00)*22)/100
elseif (y>Salaire2 && y<=Salaire3)
y=((y-81452.00)*26)/100
else(y>Salaire3)
y=((y-126264.00)*29)/100
end
disp(y)
%Thanks in advance for any tips!

2 Comments

You did not indicate what problem you are observing?
Note: you probably want to add semi-colons on the end of the assignment lines.
... and what happens when you try to run this code?

Answers (2)

Cedric - why are you subtracting the lower bound of the interval for the three highest salaries? Presumably the individual is taxed on all of their salary and not just the difference. That would be incredibly unfair as then it would benefit the individual to have a salary that is just one dollar (or whatever unit of money that is being used) more than the lower bound and so be just taxed on that single dollar. :) So just remove the subtraction and you should be able to test for your different salaries.
Also, there is an unnecessary condition with the last line of your if/elseif block
else(y>Salaire3)
The else block never has a condition applied to it (then it would be an elseif) so you can remove the y>Salaire3. It isn't harmful, just unnecessary.
Jan
Jan on 20 Feb 2016
Edited: Jan on 20 Feb 2016
Not only the last else condition is unneccessary:
if y <= Salaire1
% All values <= Salaire1 are caught here
elseif y > Salaire1 && y <= Salaire2
% Then the first test y > Salaire1 can be omitted here!
% Nicer:
elseif y <= Salaire2
This is not a bug, but clutter.

This question is closed.

Asked:

on 20 Feb 2016

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!