필터 지우기
필터 지우기

Switch results at certain condition

조회 수: 2 (최근 30일)
Amril Luqman
Amril Luqman 2021년 6월 16일
댓글: Amril Luqman 2021년 6월 17일
g=9.81; %gravity acceleration
v=input('Enter the value of Velocity');
theta=30*pi/180;
% compute and display results
disp('time of flight(s):')
time_ground=2*v*sin(theta)/g;
disp('distance travelled(m):')
distance_traveled=v*cos(theta)*time_ground;
if distance_traveled >=10
disp('Passed')
else
disp('Failed')
end
if distance_traveled>=10;
grade=A;
switch(grade)
case distance_traveled>10
fprintf('B')
case distance_traveled>15
fprintf('A')
end
I want to make the grade change at certain condition. For example, if the distance traveled is more than 10, then the grade is B. When the distance traveled is more than 15, the grade is A. Please correct what am i doing wrong here. If possible, i dont want to get rid of the switch command. Thanks in advance.

답변 (1개)

Steven Lord
Steven Lord 2021년 6월 16일
switch is not the right tool for this job. Use if instead.
switch is intended when you intend to distinguish between a fixed discrete set of possibilities.
pet = 'dog';
switch pet
case 'cat'
disp('meow')
case 'parrot'
disp('squawk')
case 'dog'
disp('bark')
otherwise
error('I don''t know what sound this type of pet makes')
end
bark
if is intended for when you have one or more criteria you want to check.
p = pi;
if p < 1
disp('less than 1')
elseif p < 2
disp('less than 2')
elseif p < 3
disp('less than 3')
else
disp('not less than 3')
end
not less than 3
  댓글 수: 1
Amril Luqman
Amril Luqman 2021년 6월 17일
Thank you, but after doing research by myself, it appear i can use these:
switch true
case (distance_traveled>10 && distance_traveled<=20)
disp('Grade C')
case (distance_traveled>20 && distance_traveled<=30)
disp('Grade B')
case (distance_traveled>=30)
disp('Grade A')
It works just like what i intented.

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

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by