Switch results at certain condition

4 ビュー (過去 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 Center および File ExchangeIntroduction 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