I need help with using a function file for assinging letter grades.

1 次查看(过去 30 天)
I'm using a fuction file to transport inputs of numerical grades into output letter grades.
Here are my two scripts
%Script 1: A1_3_8.m
%Problem 3.8A
format compact
score=input('Enter numerical grade:');
grade= lettergrade(score);
disp(grade);
%Script 2: lettergrade.m
format compact
function grade= lettergrade(score)
array=['A','B','C','D','F'];
if score < 0 || score > 100
disp('Invalid')
elseif score >= 90
grade=array(1);
elseif score >= 80
grade=array(2);
elseif score >= 70
grade=array(3);
elseif score >= 60
grade=array(4);
else
grade=array(5);
end
end
------------------------------------------------------------
I am not sure of what I am doing and need help with using a function file properly.

回答(1 个)

Walter Roberson
Walter Roberson 2019-9-9
format compact
function grade= lettergrade(score)
When you have an executable line before the first function line, then that makes the file a script file rather than a function file. script files cannot be called as functions, such as your
grade= lettergrade(score);
Also, there is a restriction that a script file cannot have a function with the same name as the script -- so function lettergrade cannot be inside script file lettergrade.m
format statements are not needed in every file: the last format executed is obeyed until you execute another format or quit MATLAB. You especially do not need a format statement inside code that does not display any output.

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

标签

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by