Switch-case force problem

조회 수: 1 (최근 30일)
Aiden Estle
Aiden Estle 2021년 3월 24일
답변: Image Analyst 2022년 5월 28일
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
Aiden Estle
Aiden Estle 2021년 3월 24일
편집: Aiden Estle 2021년 3월 24일
Okay thank you, that fixed the problem I had with the inputs. I can now input the weight and it asked for the coefficient value, but shouldn't it run through each case and get the value of m to use for the coeff? Also how do I get it to print the f value after each case?
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
Walter Roberson
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
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:

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by