Help restricting non whole numbers in a script

3 ビュー (過去 30 日間)
John Furman
John Furman 2020 年 1 月 29 日
編集済み: John D'Errico 2020 年 1 月 29 日
I am working on a script that asks for an input to be given between 1 and 100. I would like to have the restriction that the input is limited to between 1 and 100, and that the number must be a whole number.Here is the code:
number=input('Enter a whole number between 1 and 100:')
while number<1 || number>100
display('Not a valid number please try again')
number=input('Enter a whole number between 1 and 100:')
end
I can't figure out how to get it to set a restriction to non-whole number values. Please let me know how to specify this. I have been searching for a while and haven't found the solution.

回答 (1 件)

John D'Errico
John D'Errico 2020 年 1 月 29 日
編集済み: John D'Errico 2020 年 1 月 29 日
A very easy check is just:
rem(number,1) ~= 0
So if number has a fractional part, then rem(number,1) will return that fractional part. Then I tested to see if the fractional part was zero.
Slightly shorter is just
~rem(number,1)
but that is I think less obvious. Try it out though. What does that code fragment return when number has a fractional part? Does it return true or false? What does it do when number is a pure integer?

カテゴリ

Help Center および File ExchangeSimulink についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by