elseif to switch statement

조회 수: 14 (최근 30일)
Gerardo Echeverria
Gerardo Echeverria 2020년 4월 20일
편집: Adam Danz 2020년 4월 20일
I am attempting to switch this into a switch statement.
TestScore = input('Enter a score from the keyboard ')
if(TestScore > 89)
disp('Your Letter grade is A')
elseif(TestScore > 79)
disp('Your Letter grade is B')
elseif(TestScore > 69)
disp('Your Letter grade is C')
elseif(TestScore > 59)
disp('Your Letter grade is D')
else
disp('Your Letter grade is F')
end

채택된 답변

Adam Danz
Adam Danz 2020년 4월 20일
편집: Adam Danz 2020년 4월 20일
There's nothing wrong with the if/elseif/else syntax but the conditional statements could be tightened up.
If you prefer a switch-case,
switch true
case (TestScore > 89 && TestScore <=100)
disp('Your Letter grade is A')
case (TestScore > 79 && TestScore <= 89)
disp('Your Letter grade is B')
case (TestScore > 69 && TestScore <= 79)
disp('Your Letter grade is C')
case (TestScore > 59 && TestScore <= 69)
disp('Your Letter grade is D')
case (TestScore >=0 && TestScore <= 59)
disp('Your Letter grade is F')
otherwise
disp('TestScore did not match grade ranges.')
end
  댓글 수: 2
Gerardo Echeverria
Gerardo Echeverria 2020년 4월 20일
This is what I got, It seems to be different, but they both work. Do you know if this one is incorrect?
TestScore = input('Enter a score from the keyboard ');
switch TestScore
case num2cell(90:100)
disp('Your Letter grade is A')
case num2cell(80:89)
disp('Your Letter grade is B')
case num2cell(70:79)
disp('Your Letter grade is C')
case num2cell(60:69)
disp('Your Letter grade is D')
otherwise
disp('Your Letter grade is F')
end
Adam Danz
Adam Danz 2020년 4월 20일
편집: Adam Danz 2020년 4월 20일
Test the following grades:
  • 101 (accidentally entered by user)
  • 91.5

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 GNC and Avionics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by