How can I use a while loop to check if user input is an integer?

I want the user to input a non zero even interger. However with my current code, even non zero intergers like '2' aren't recognised as so. I could remove the ~(isinteger(a) but then the code fails when user inputs a decimal. How can i incoporate it to say that the number inputted must be an integer.
prompt= 'enter non zero even integer'
z= input(prompt)
n= rem(z,2);
while (n==1)|| (a==0)||~(isinteger(z))
z= input ('try again');
n= rem(z,2);
end
disp('This number is a non zero even integer');

 採用された回答

Adam Danz
Adam Danz 2019 年 1 月 24 日
編集済み: Adam Danz 2019 年 1 月 24 日

0 投票

The while loop will continually ask for a non-zero even integer until one is entered.
prompt= 'enter non zero even integer '
z = 0;
while z=0 || mod(z,2)~=0
z= input(prompt)
end
If you'd like to avoid negative numbers, too,
while z<=0 || mod(z,2)~=0

3 件のコメント

adena0
adena0 2019 年 1 月 24 日
i'd like to incoporate a "try again" element to it when the number inputted is wrong. how could i do this? Thank you
Adam Danz
Adam Danz 2019 年 1 月 24 日
編集済み: Adam Danz 2019 年 1 月 24 日
prompt= 'enter non zero even integer ';
z= input(prompt);
while z=0 || mod(z,2)~=0
prompt = 'try again '; %but now the reader won't know the limitations
z= input(prompt)
end
adena0
adena0 2019 年 1 月 24 日
thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

質問済み:

2019 年 1 月 24 日

コメント済み:

2019 年 1 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by