嘿,我在這裏得到一個奇怪的錯誤。這個函數只是找到一個數字的正確除數並返回它們。整數操作數錯誤
function [divisors] = SOEdivisors(num)
%SOEDIVISORS This function finds the proper divisors of a number using the sieve
%of eratosthenes
%check for primality
if isprime(num) == 1
divisors = [1];
%if not prime find divisors
else
divisors = [0 2:num/2]; %hard code a zero at one.
for i = 2:num/2
if divisors(i) %if divisors i ~= 0
%if the remainder is not zero it is a divisor
if rem(num, divisors(i)) ~= 0
%remove that number and all its multiples from the list
divisors(i:i:num/2) = 0;
end
end
end
%add 1 back and remove all zeros
divisors(1) = 1;
divisors = divisors(divisors ~= 0);
end
end
我收到的錯誤是:
Integer operands are required for colon operator when used as index
它指的是線23
線23
divisors(i:i:num/2) = 0;
但我我和num都應該是整數。 ..我知道我是一個整數。但即使當我嘗試
num = int8(num)
或類似的東西,我仍然得到錯誤。
感謝您的閱讀!
實際上,如果你強制num是int類型的,你不應該得到這個錯誤(也許是一個不同的錯誤)。見'int8(5)/ 2'。 ----旁註:如果你不需要,不要強迫matlab使用數字轉換爲整數,它可能會讓你感到意外,通常不會被要求。 –