Help restricting non whole numbers in a script
3 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
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?
0 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!