function using if or switch statement
显示 更早的评论
I am going to make a function called XYZ that takes as its only input argument one positive integer specifying the year of birth of a person and returns as its only output argument the name of the generation that the person is part of ('X', 'Y', or 'Z ') according to the table below. For births before 1966, return 'O' for Old and for births after 2012, return 'K' for Kid . Remember that to assign a letter to a variable, you need to put it in single quotes,
I have make that code
function born=generationXYZ(n)
if 1966<=n<=1980
born='X';
end
if 1981<=n<=1999
born='Y';
end
if 2000<=n<=2012
born='Z';
end
if n<=1966
born='O';
end
if n=>2012
born='K';
end
end
but when i test this code i getting an error when i remove last two if check i always recipe z in output.
I know it can make with switch statement kindly refer me where i need corrections. Thanks in advance for assistance....
采纳的回答
更多回答(1 个)
Walter Roberson
2015-5-20
0 个投票
The expression 1966<=n<=1980 is interpreted as ((1966<=n)<=1980) . The first subpart of that, (1966<=n), returns a logical value, 0 for false and 1 for true. That value is then tested against <= 1980 and since 0 and 1 are both <= 1980, the result is always true.
You need 1966 <= n && n <= 1980
You also need to look more carefully at how you are treating the exact year 1966 and how you are treating the exact year 2012
4 个评论
Muhammad Usman Saleem
2015-5-20
编辑:Walter Roberson
2015-5-20
Muhammad Usman Saleem
2015-5-20
Walter Roberson
2015-5-20
if 2012 > n then n < 2012 so that test is checking for dates before 2012.
Note: there is no reason to keep checking 1966. Test 1966 first, and if that is false then you know the value must be at least 1966 and need not test against 1966 again.
Muhammad Usman Saleem
2015-5-20
类别
在 帮助中心 和 File Exchange 中查找有关 Software Development 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!