Switch-case force problem
1 次查看(过去 30 天)
显示 更早的评论
I'm trying to write a code for using the switch-case structure to figure out the force needed to move an object for each case where the coefficient of friction is
metal on metal: u=0.2
wood on wood: u=0.35
metal on wood: u=0.40
rubber on concrete: u=0.70
w: the user inputs any weight
m: the different u values of each case
I'm am trying to print each force value of w*u for each case and then end the code. This is what I have right now, can I get a hand on how to fix the code?
for w=input('enter weight of object',s)
m = input('static friction coefficient',s);
switch m
case u == 0.2;
f=u*w;
case u == 0.35;
f=u*w;
case u == 0.40;
f=u*w;
case u == 0.70;
f=u*w;
end
end
3 个评论
Walter Roberson
2021-3-24
u=2; for m=1:2;switch m; case u==1; disp('m1'); case u==2; disp('m2'); otherwise disp('m??') ; end;end
m2 m??
u=2; for m='12';switch m; case u==1; disp('m1'); case u==2; disp('m2'); otherwise disp('m??'); end;end
m?? m??
Why does the string execute twice instead of once (answer: '12' is a vector of values and for executes once per value)
Why does m=1 lead to m2 being displayed and m=2 lead to m?? being displayed?
Consider m=1 then switch m causes m (1) to be compared to u==1 first. u=2 so u==1 is false which is 0. Is m (1) equal to false (0)? No. So the first case is not matched. Second case is u==2 which is true. m is 1 and 1 equals true so the case is taken and m2 is printed.
Consider m=2. u== some value is 0 (false) or 1 (true) and neither of those can equal m which is 2, so you take the otherwise.
Now let m='1'. '1' is the character 1 and when you compare characters (switch) to numbers (0 or 1, false or true), then the character position in Unicode is used, and the character position for '1' is 49. But 49 never compares equal to 0 or 1.
回答(1 个)
Image Analyst
2022-5-28
If you want ranges for u personally I'd use an if/else, though you can use switch if you make the conditions correctly. But don't compare u to exact numbers with equals signs. Why not? Read the FAQ:
0 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!