以下工作原理如何?
Algorithm 1 Sum of numbers in an Array
Function SUMMATION (Sequence)
sum <---0
for i <----1 to Length (Sequence) do
Sum <--- Sum + sequence[i]
end for
return sum
答案 0 :(得分:4)
基本上说如果从数组的开头(它的第一个元素)开始,并且在每个元素处将该元素的值添加到运行总计中,当你到达最后一个元素(序列的长度)时,你' ll具有数组值的总和。
# This says "we have a function called SUMMATION. It requires a sequence
Function SUMMATION (Sequence)
# This says "assign the value 0 to variable 'sum'
sum <---0
# This says "make variable 'i' go from 1 to the length of the sequence"
for i <----1 to Length (Sequence) do
# This says "assign 'sum + the ith value in the sequence' to variable 'sum'
Sum <--- Sum + sequence[i]
# This indicates we're done with the loop, so loop back to the top, or
# continue on if we're done looping
end for
# This just returns the value 'sum' to the calling procedure
return sum
我们这里所拥有的不是任何特定的语言。相反,它是“伪代码” - 它意味着看起来像代码,以传达算法或其他与代码相关的想法,但故意意味着不是在特定的语言。通过这种方式,任何阅读代码而不需要了解特定语言的人都可以更容易地访问它。
答案 1 :(得分:0)
翻译成java?
int algorithm (int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
}