2013-10-10 56 views
0

嘿,我在這裏得到一個奇怪的錯誤。這個函數只是找到一個數字的正確除數並返回它們。整數操作數錯誤

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) 

或類似的東西,我仍然得到錯誤。

感謝您的閱讀!

+0

實際上,如果你強制num是int類型的,你不應該得到這個錯誤(也許是一個不同的錯誤)。見'int8(5)/ 2'。 ----旁註:如果你不需要,不要強迫matlab使用數字轉換爲整數,它可能會讓你感到意外,通常不會被要求。 –

回答

1

如果num是奇數則num/2不是整數...

0

你行只包含用於索引兩個部分。

i 

num/2 

正如你已經提到inum是整數的唯一合乎邏輯的解釋是,num是奇數。

然後num/2不會是整數。


也許你有興趣使用fix(num/2)(這是將有效地爲divisors的cretion使用),否則可能roundceil

0

當使用:

在命令的代碼就意味着你知道結果是例如0.1或0.2或2.1的非點號。你應該有1或2或21。 您的結果也必須是無符號數字。例如:1或2或21不是-1或-2或-21。

然後使用帶符號的int類型或從「fix();」命令中使用。 例如:

a=2.1; 

a=fix(a);那麼「a」值將是2; 祝你有美好的一天。