我是Java的新手,我正在做一个单一的课程。我被要求设计三个函数。我必须找到数组中每个相邻数字之间的差异,另一个是数组的总和,最后一个用其他函数计算差异然后编写一个程序。我完全迷失在最后一个功能上,而我的导师已经离开了。这是我到目前为止所做的代码。我不希望别人为我做代码,但如果有人能告诉我我需要做什么,我将不胜感激。我不确定如何将差异函数循环到数组中并将其存储到我已经创建的新数组中。如果有人能解释我哪里出错了,我很乐意听取你的意见!
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 :(得分:1)
你的函数“calculateDifferences”的实现是不正确的。
这个功能应该是这样的:
function calculateDifferences()
{
var createArray = new Array(numberArray.length);
for(var c = 0; c&lt; 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;
}
答案 1 :(得分:0)
您应该使用与createArray
相同的方式对numberArray[c]
进行索引。