score= randi(100);
if score < 20
grade= 'D';
print grade
elseif score < 40
grade= 'C';
print grade
elseif score < 60
grade= 'B';
print grade
elseif score < 80
grade= 'B+';
print grade
else
grade= 'A';
print grade
end
i tried to run a basic if else loop but no matter what score i input in the command wndow, my answer is always 'A'.

 채택된 답변

KSSV
KSSV 2023년 3월 15일

0 개 추천

score= randi(100);
if score < 20
grade = 'D';
elseif score < 40
grade= 'C';
elseif score < 60
grade= 'B';
elseif score < 80
grade= 'B+';
else
grade= 'A';
end
disp(grade)

추가 답변 (1개)

Dyuman Joshi
Dyuman Joshi 2023년 3월 15일
편집: Dyuman Joshi 2023년 3월 15일

1 개 추천

if-else is not a loop, they are conditional statements.
If you want to print/display something, use sprintf or fprintf or disp. However, if you want see the value of a variable, type the variable name without using semi colon
score= randi(100)
score = 52
if score < 20
grade= 'D';
elseif score < 40
grade= 'C';
elseif score < 60
grade= 'B';
elseif score < 80
grade= 'B+';
else
grade= 'A';
end
grade
grade = 'B'

댓글 수: 6

Waqar
Waqar 2023년 3월 15일
Hi. Thank you for your response. However, I still couldn't run the code. On the command window when I assign a value to the score:
score= 33
the grade output is random:
grade
= 'A'
May I know what am I doing wrong here? Thanks!
Dyuman Joshi
Dyuman Joshi 2023년 3월 15일
편집: Dyuman Joshi 2023년 3월 15일
Are you running your whole code on command window? or are you running a script?
Variables you define via command window are not accessible to the script.
Also, in a script, when you change the value of any variable, you need to run your script again to update the result.
Waqar
Waqar 2023년 3월 15일
While running the script, it's working fine. But I wanted to enter values in the command window as input and see if the grades correspond to them
"But I wanted to enter values in the command window as input and see if the grades correspond to them "
As I said above, Variables you define via command window are not accessible to the script.
A better alternative would be to use a function -
%You can call the function directly
fun(25)
ans = 'C'
%or define a variable and use variable as input
score=randi(100)
score = 80
fun(score)
ans = 'A'
%calling the function again with a different value
fun(75)
ans = 'B+'
%change the value of score and call the function again
score=randi(100)
score = 29
fun(score)
ans = 'C'
function grade = fun(score);
if score < 20
grade= 'D';
elseif score < 40
grade= 'C';
elseif score < 60
grade= 'B';
elseif score < 80
grade= 'B+';
else
grade= 'A';
end
end
Waqar
Waqar 2023년 3월 15일
Worked! Thanks a lot!
Dyuman Joshi
Dyuman Joshi 2023년 3월 15일
You are welcome!

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2022b

질문:

2023년 3월 15일

댓글:

2023년 3월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by