2014-09-04 122 views
0

我想創建一個大小爲n的數組,其中n由循環的變量定義,但我不知道如何預先計算數組的大小。 我們可以假設,開始<末和步> 0計算數組的大小

int start; // Initialized by user 
int end; // Initialized by user 
int step; // Initialized by user 

int size = ? // What is the formula for the size ? 

Object[] array = new Object[size]; 
int index=0; 

for(int i=start; i<=end; i+=step){ 
    array[index++]=new Object(); 
} 

我可以只使用一個列表,然後將元素複製到一個數組,但似乎像一個彎路。

:(結束 - 開始)/大小

回答

0
int size = ceiling(float(end - start + 1)/size); 

需要,因爲你使用i <= end,所以它必須包括終值添加1

+0

start = 3,end = 7,step = 2。迭代3次,但(7-3 + 1)/ 2 = 2。我不認爲增加天花板功能可以解決問題,是嗎? – user 2014-09-04 02:45:59

+0

是的,我認爲'天花板'是對的。 – Barmar 2014-09-04 02:48:30