2010-02-18 133 views
0

我是新來的Java,我正在做一個單一的課程。我被要求設計三個函數。我必須找到數組中每個相鄰數字之間的差異,另一個是總數和最後一個使用其他函數計算差異,然後編寫一個程序。我完全失去了最後一個功能,我的導師已經離開了Hols。這是我迄今爲止完成的代碼。我不希望人們爲我做代碼,但如果有人能告訴我我需要做什麼,我會很感激你的建議。我不知道如何將差異函數循環到數組中,並將其存儲到我創建的新數組中。如果有人能夠解釋我出錯的地方,我很樂意聽到你的消息!如何用另一個函數在一個函數中創建一個循環?

var numberArray = [10,9,3,12]; 

// function difference will find the highest value of the two numbers,find the difference between them and return the value. 

function difference(firstNumber, secondNumber) 

{ 

if (firstNumber > secondNumber) 
{ 
    return (firstNumber - secondNumber); 
} 
else 
{ 
    return (secondNumber - firstNumber); 
} 

} 
// function sum will add the total numbers in the array and return the sum of numbers. 

function sum(numberArray) 
{ 
numberTotal = 0 
for (var total = 0; total < numberArray.length; total = total + 1) 
{ 
numberTotal = numberTotal + numberArray[total] 
} 
{ 
    return numberTotal 
} 

/*code the process that calculates a new array containing the differences between all the pairs 
of adjacent numbers, using the difference() function you have already written. 
This function should be named calculateDifferences() and should accept an array numberArray. 
The function should first create a new empty array of the same size as numberArray 
It should then calculate the differences between the pairs of adjacent numbers, 
using the difference() function, and store them in the new array. Finally, the function should return the new array. 
The calculation of the differences should be done in a loop, at each step finding the difference between each 
array element and the next one along in the array, all except for the last difference, 
which must be dealt with as a special case, because after the last element we have to wrap round to the start again. 
So the final difference is between the last and first elements in the array.*/ 


function calculateDifferences() 
var createArray = new Array (numberArray.length); 
{ 
createArray = 0; 
for (var c = 0; c < numberArray.length; c = c + 1) 
{ 
    createArray = difference(numberArray[c]); 
} 
{ 
return createArray 
} 
} 
+0

家庭作業? _____ – kennytm 2010-02-18 12:01:30

+1

你確定它不是Javascript嗎? – 2010-02-18 12:01:52

+0

這不是Java ...可能想要確保你的語言是正確的。此外,正確的縮進讓世界變得更美好,所以請做好 – CheesePls 2010-02-18 12:06:19

回答

1

您的函數「calculateDifferences」的實現不正確。
這個功能應該是這樣的:

功能calculateDifferences()
{
變種createArray =新陣列(numberArray.length);
爲(VAR C = 0; C^< numberArray.length - 1; C = C + 1) {
/*
因爲函數 「差」 的有兩個參數(firstNumber,secondNumber)在其聲明中,我們應該提出兩個論點。 (即陣列中的相鄰元素)
*/
createArray [c] = difference(numberArray [c],numberArray [c + 1]); }
/*
計算數組的第一個元素和最後一個元素的差異,並將其分配給返回數組的最後一個元素。
*/
createArray [numberArray.length - 1] = difference(numberArray [0],numberArray [numberArray.length - 1]);
return createArray;
}

+0

非常感謝你向我解釋這一點。我不知道我哪裏出了問題,但你現在解釋它的方式對我來說是有意義的。我認爲-1是告訴它循環直到數組的結尾? – newuser 2010-02-18 15:55:18

0

你應該指數createArray你已經做numberArray[c]以同樣的方式。

+0

謝謝,我會放棄它。 – newuser 2010-02-18 12:20:35

相關問題