While Loop Question - Will not Properly Execute

% Until good gender, prompt user to enter the gender
y = input ( 'Is the person female(1) or male(2)? Enter 1 or 2: ' );
while (y ~= 1) || (y ~= 2)
disp( 'not 1 or 2' )
y = input ( 'Is the person female(1) or male(2)? Enter 1 or 2: ' );
end
Can anyone tell me why this will not properly execute when ran through MATLAB?

 採用された回答

Geoff Hayes
Geoff Hayes 2019 年 2 月 14 日

0 投票

Josh - consider your conditions for the while loop
while (y ~= 1) || (y ~= 2)
which is saying that if the input is not 1 (female) or not 2 (male) then ask the user to enter in a gender again. What you really want to say is if the input is not 1 AND not 2 then... (i.e. not female and not male) and so your code becomes
while (y ~= 1) && (y ~= 2)

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2018a

質問済み:

2019 年 2 月 14 日

回答済み:

2019 年 2 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by