Help restricting non whole numbers in a script

4 visualizzazioni (ultimi 30 giorni)
John Furman
John Furman il 29 Gen 2020
Modificato: John D'Errico il 29 Gen 2020
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.

Risposte (1)

John D'Errico
John D'Errico il 29 Gen 2020
Modificato: John D'Errico il 29 Gen 2020
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?

Categorie

Scopri di più su Simulink in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by