Can't run my 'if, elseif, else' code
显示 更早的评论
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'.
采纳的回答
更多回答(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)
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
6 个评论
Waqar
2023-3-15
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
2023-3-15
"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)
%or define a variable and use variable as input
score=randi(100)
fun(score)
%calling the function again with a different value
fun(75)
%change the value of score and call the function again
score=randi(100)
fun(score)
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
2023-3-15
Dyuman Joshi
2023-3-15
You are welcome!
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!