2010-02-18 199 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