我正在编写一个计算整数阶乘的程序。但是,我坚持的部分是如果有人输入1.3
之类的非整数,我希望能够测试输入并显示"The number you have entered is not an integer"
答案 0 :(得分:27)
您可以使用mod
函数,该函数返回除法后的余数。所有整数都可以被1
整除。所以对非整数的一个很好的测试是
integerTest=~mod(value,1);
如果0
不是整数,则返回value
,如果是1
,则返回{{1}}。然后,您可以将其用作条件来拒绝非整数用户输入。
答案 1 :(得分:22)
以下是另一种变体(您可以看到它在ISIND函数中使用:edit isind.m
):
integerTest = ( x == floor(x) );
在我的机器上,它比其他提议的解决方案更快:
%# 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) )
时序:
Elapsed time is 0.012253 seconds.
Elapsed time is 0.014201 seconds.
Elapsed time is 0.005665 seconds.
答案 2 :(得分:4)
您可以将值转换为整数并返回到double,并根据原始值检查结果:
>> x = 1.3; >> x == double(uint64(x)) ans = 0 >> x = 2; >> x == double(uint64(x)) ans = 1
有趣的是,使用MOD的R.M.'s approach在循环中运行得更快,并且上面的转换方法在向量化时运行得更快:
>> x = rand(100000, 1); >> tic; for ii = 1:100000; ~mod(x(ii), 1); end; toc; Elapsed time is 0.018380 seconds. >> tic; for ii = 1:100000; x(ii) == double(uint64(x(ii))); end; toc; Elapsed time is 0.383020 seconds. >> tic; ~mod(x, 1); toc; Elapsed time is 0.005299 seconds. >> tic; x == double(uint64(x)); toc; Elapsed time is 0.002971 seconds.
答案 3 :(得分:2)
assert(isnumeric(input) && round(input) == input, 'That number is not an integer.')
您也可以轻松添加其他支票(如积极性)。
使用isinteger
进行编辑。感谢@SolarStatistics
,我没有注意到他们添加了此功能。
由于isinteger
不适合,请再次编辑回原始答案(请参阅下面的评论)。
答案 4 :(得分:0)
正如@nibot isinteger 所指出的那样,输入为整数TYPE。相反,您可以检查舍入输入是否返回与输入相同的值。例如:
assert(abs(round(input)-input))<eps*2,'That number is not an integer.')
例如
>> input=1.3;
>> assert(abs(round(input)-input)<eps*2,'That number is not an integer.')
??? That number is not an integer.
>> input=3;
>> assert(abs(round(input)-input)<eps*2,'That number is not an integer.')
>>
答案 5 :(得分:0)
我只是想指出所提供的方法都测试输入是否是高斯整数,这意味着实部和虚部都是 整数。如果你需要关心想象部分,那么你需要单独处理它。
对于我的应用程序,假想组件的输入不应被视为有效整数,所以我有这个:
function boolResult = fnIsInteger(input)
%validate input
if isempty(input)
error('Input cannot be empty')
elseif ~isnumeric(input)
error('Input must be numeric')
end
boolResult = (imag(input) == 0) & (round(input) == input);
end
使用b3。的测试:
>> x = rand(100000, 1);
>> tic; for ii = 1:100000; ~mod(x(ii), 1); end; toc;
Elapsed time is 0.003960 seconds.
>> tic; for ii = 1:100000; fnIsInteger(x(ii)); end; toc;
Elapsed time is 0.217397 seconds.
>> tic; ~mod(x, 1); toc;
Elapsed time is 0.000967 seconds.
>> tic; fnIsInteger(x); toc;
Elapsed time is 0.003195 seconds.
循环调用相当慢,主要是由于函数开销。用~mod(dataInput,1)替换算术表达式将使其仅比检查虚部的代码快50%。
答案 6 :(得分:-1)
通过double
命令,您无法得到正确的答案:
>> double(uint64(21/22))
ans =
1
>> double(uint64(22/22))
ans =
1
floor
,round
,......此类案件存在问题:
floor(22/22)==21.99999999999999999999999999999999999/22
但mod
似乎可以区分22/22
和21.99999999999999999999999999999999999/22
:
>> mod(22,22)
ans =
0
>> (21.99999999999999999999999999999999999/22)
ans =
1