function used for grading, :how do i get it to work?
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I am trying to get this code to work, as far as i know I am meant to use "else" for the last error to be displayed when a negative number is inserted, this isn't working for me. when I leave it as "if", it works by giving me the error message I want it to but also gives out the grade E. When a value over 100 is entered it displays the error message i want and no grade comes up. Is this code ok as it is or what am I missing? Thanks for your help in advance.
function output= grade(mark)
if mark>100
disp('error, mark can not be more than 100');
elseif mark>=75
disp('A');
elseif mark>=60
disp('B');
elseif mark>=50
disp('C');
elseif mark>=40
disp('D');
elseif mark<40
disp('E')
if mark<0
disp('error, mark can not be less that 0');end
end
2 commentaires
Réponses (1)
Steven Lord
le 5 Mar 2021
I would do my input argument checking up front. Why go through the effort of classifying data that I know is invalid?
if mark > 100
error('The mark is too high, the maximum mark is 100.')
end
if mark < 0
error('The mark is too low, the minimum mark is 0.')
end
Now after those if mark is a real finite scalar value I know it has to be in the interval [0, 100]. Now I can classify that data using the if / elseif / else / end construct.
But not that your code never assigns a value to the output variable, so if anyone called this with an output argument your code would throw an error. You probably want to assign the letter grade to the output argument rather than just displaying it.
output= grade(80); % will error
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!