Switch results at certain condition
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
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
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!