I am having some issues calculating grades using matlab.

Hello, I am having some issues getting the program to correctly calculate grades. It works when the range of x is between 90 and 100, but anything below displays incorrectly. For the first part of the question, I cannot use elseif statements, only if. I feel that once I figure this part out, the second part where I use elseif statements will be much easier. Here is my code:
x = 80;
if x >=90;
grade = 'A';
if x <= 89, x >= 80;
grade = 'B';
if x <= 79, x >= 70;
grade = 'C';
if x <= 69, x >= 60;
grade = 'D';
if x < 60;
grade = 'F';
end;
end;
end;
end;
end;
disp(grade)
Any help would be very much appreciated!
Thanks, Nick

댓글 수: 1

I meant to also include the error I am receiving when I enter something below 90. This is what I am seeing:
Undefined function or variable 'grade'.

댓글을 달려면 로그인하십시오.

 채택된 답변

Jan
Jan 2015년 10월 15일
편집: Jan 2015년 10월 15일
At first change:
if x <= 89, x >= 80
to:
if x <= 89 & x >= 80
The comma evaluates the expression "x >= 80" without any effects to the previous if command.
Then check the logic again:
if x >=90
grade = 'A';
if x <= 89 & x >= 80
When x is greater than 90, then it cannot be between 80 and 89. So you need:
if x >=90
grade = 'A';
elseif x <= 89 & x >= 80
This can be simplified: If "x >= 90" has been checked already, the test for "x <= 89" is redundant and can be omitted.

댓글 수: 1

Thank you very much! The first part of the question explicitly states to not use elseif statements, but the info that you have provided me allowed me to fix my code to display correctly. Since I wasn't able to use elseif, I just ended each statement and created a new if statement for each case. Seems to work beautifully!
Thanks again,
Nick

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Chad Greene
Chad Greene 2015년 10월 15일
Or more succinctly,
x = 80;
letters = {'F','D','C','B','A'};
disp(letters{min([ max([floor((x-50)/10) 0])+1 5])})

카테고리

제품

태그

질문:

2015년 10월 15일

답변:

2015년 10월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by