如何在MATLAB中测试整数?

Rya*_*yan 18 matlab integer

我正在编写一个计算整数阶乘的程序.但是,我坚持的部分是如果有人输入非整数,例如1.3,我希望能够测试输入和显示 "The number you have entered is not an integer"

abc*_*bcd 27

您可以使用该mod函数,它返回除法后的余数.所有整数都可被整除1.所以对非整数的一个很好的测试就是

integerTest=~mod(value,1);
Run Code Online (Sandbox Code Playgroud)

0if 返回if value不是整数,1如果不是则返回.然后,您可以将此作为条件来拒绝非整数用户输入.


Amr*_*mro 22

这是另一个变体(你可以看到它在ISIND函数中使用:)edit isind.m:

integerTest = ( x == floor(x) );
Run Code Online (Sandbox Code Playgroud)

在我的机器上,它比其他提议的解决方案更快:

%# create a vector of doubles, containing integers and non-integers
x = (1:100000)';                       %'
idx = ( rand(size(x)) < 0.5 );
x(idx) = x(idx) + rand(sum(idx),1);

%# test for integers
tic, q1 = ~mod(x, 1); toc
tic, q2 = x==double(uint64(x)); toc
tic, q3 = x==floor(x); toc

%# compare results
assert( isequal(q1,q2,q3) )
Run Code Online (Sandbox Code Playgroud)

时序:

Elapsed time is 0.012253 seconds.
Elapsed time is 0.014201 seconds.
Elapsed time is 0.005665 seconds.
Run Code Online (Sandbox Code Playgroud)

  • @ChristopherBarber:好的,然后我们应该添加`isfinite`来捕获Inf和NaN的情况,如:`integerTest = isfinite(x)&(x == floor(x));` (2认同)
  • @ChristopherBarber:如果你真的想要彻底,你也应该测试数字是非复杂的`isreal` (2认同)

Mat*_*ter 2

assert(isnumeric(input) && round(input) == input, 'That number is not an integer.')

您也可以轻松添加其他检查(例如积极性)。

编辑使用isinteger. 谢谢@SolarStatistics,我没有注意到他们添加了这个功能。再次编辑回原始答案,因为isinteger不合适(请参阅下面的评论)。

  • “isinteger”可能不是我们想要的,因为它检查整数类型。OP可能需要一个条件检查,比如“x - fix(x) == 0”或“x - fix(x) &lt; eps”,适用于双打。 (5认同)