i am trying to fool proof my code. If i were to put 3 as the input for the varible, unit; it will loop back one but then skip a couple of commands.
Sorry, if my explainantion doesn't make sense :)
This screenchot is me just following the directions:
Now if I were to try and enter a number other than 1 or 2:
function [vf, k]=hhvelocity10
clc
close all
format compact
fprintf('\n')
unit=input(['Enter 1 to work with an initial velocity or enter 2 to work \n ' ...
'with a pre-selected initial velocity = '],'s');
fprintf('\n')
initialvelocity='1';
preinitialvelocity='2';
if contains (unit,initialvelocity)
g=9.8;
InitialVelocity=input('Please give me the Initial Velocity in meters per second = ');
fprintf('\n')
InitialHeight=input('Please give me the Initial Height in meters = ');
fprintf('\n')
y=InitialHeight;
v=InitialVelocity;
vf=sqrt(2*g*y+v.^2);
fprintf('The velocity is %.2f m/s \n', vf);
fprintf('\n')
elseif contains (unit,preinitialvelocity)
fprintf('Your pre-selected velocity is 10 m/s. \n')
fprintf('\n')
g=9.8;
InitialHeight=input('Please give me the Initial Height in meters = ');
fprintf('\n')
y=InitialHeight;
v=10;
vf=sqrt(2*g*y+v.^2);
fprintf('The velocity is %.2f m/s \n', vf);
fprintf('\n')
else
(unit~=1 || unit~=2);
disp('Please enter 1 or 2.')
unit=input(['Enter 1 to work with an initial velocity or enter 2 to work \n ' ...
'with a pre-selected initial velocity = '],'s');
fprintf('\n')
end
mu=input(['Please enter the coefficient of friction of the rough \n' ...
'horizontal surface = ']);
fprintf('\n')
m=input('Please enter the mass of the object in kg = ');
fprintf('\n')
f=mu*m*g;
x=input(['Please enter the distance you want the object to travel on \n' ...
'the rough horizontal region in meters = ']);
fprintf('\n')
x_s=input(['How far would you like for the object to compress \n' ...
'the spring in meters? ']);
fprintf('\n')
v_f=vf;
v_i=v_f;
x_f=x_s;
k=(2*(-f)*(x+x_s))/(x_f.^2)+(m*v_i.^2)/(x_f.^2);

댓글 수: 2

Dyuman Joshi
Dyuman Joshi 2022년 5월 2일
So if I am understanding it correctly, If someone enters a value other than 1/2, you want to ask them to enter again, either 1 or 2?
Miya Harris
Miya Harris 2022년 5월 2일
Yes.

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

 채택된 답변

Voss
Voss 2022년 5월 2일

0 개 추천

Typically you'd ask the user for input and check that the input is valid inside a while loop, because you need to keep asking until the given input is valid. Something like this:
unit = ''; % initialize to some invalid input value
while ~ismember(unit,{'1' '2'}) % iterate while unit is invalid
unit=input(['Enter 1 to work with an initial velocity or enter 2 to work \n ' ...
'with a pre-selected initial velocity = '],'s');
fprintf('\n')
end

추가 답변 (0개)

카테고리

질문:

2022년 5월 2일

댓글:

2022년 5월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by