function used for grading, :how do i get it to work?

7 Ansichten (letzte 30 Tage)
Matthew Campbell
Matthew Campbell am 5 Mär. 2021
Kommentiert: Matthew Campbell am 5 Mär. 2021
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 Kommentare
Cris LaPierre
Cris LaPierre am 5 Mär. 2021
You have a syntax error. You are missing a closing end.
Perhaps going through Ch 13 of MATLAB Onramp will help (at least the section on if statements).
Matthew Campbell
Matthew Campbell am 5 Mär. 2021
It did help, thank you.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Steven Lord
Steven Lord am 5 Mär. 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
  1 Kommentar
Matthew Campbell
Matthew Campbell am 5 Mär. 2021
I got it now, it is a tutorial question for uni. Have to do what they want and the error messages are part of it. thanks

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by