Repeat input prompts until conditions are met or until prompts asked 3 times

30 次查看(过去 30 天)
I have three input prombts and I'm supposed to ask the user to input values until the conditions are met. The values for each prompt must be greater than zero and the last prompt has to have a length of 3.
The three prombts are
W=input('Type the values of W:');
d=input('Type the values of d:');
Er=input('Type the value of Er:');
I'm supposed to use a while loop to repeat the prompts until the conditions are met or to simply stop once the user has inputted the wrong values for the third time. Everytime I try to make the while loop it either loops forever if the conditions aren't met or it simply takes the values given even if they are wrong. How can I use a while to repeat the input prompts ony three times if the conditions aren't met.

采纳的回答

Joseph Wilson
Joseph Wilson 2020-12-4
%%%No matter what, your issue of " it simply takes the values given even if they are wrong." is going to occur since MATLAB is %going to store that value. The IF statement however send and error message and ends the script if the condition isn't met.
W=input('Type the values of W:');
W_count = 1;
while W <= 0 && W_count <3
W=input('Type the values of W:');
W_count = W_count+1;
end
if W<=0
error('Invalid input for W, value must be positive')
end
d=input('Type the values of d:');
d_count = 1;
while d <= 0 && d_count <3
d=input('Type the values of d:');
d_count = d_count+1;
end
Er=input('Type the value of Er:');
Er_count = 1;
while Er ~= 3 && Er_count <3
Er=input('Type the value of Er:');
Er_count = Er_count+1;
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by