필터 지우기
필터 지우기

Help restricting non whole numbers in a script

조회 수: 2 (최근 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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by