# 返回的翻译部分：需要一个能够将数组相乘并在数组为空时返回0的代码。

go评论31阅读模式

Need code that multiplies arrays, and returns 0 if array is empty

# 问题

Here is the translated code:

``````我需要一个代码，它会将由测试形成的数组内容相乘

public void testMulArray() {
FirstSteps firstSteps = new FirstSteps();
int[] array1 = {1, 2, 3};
assertEquals(6, firstSteps.mul(array1));
int[] array2 = {-1, -2, 3};
assertEquals(6, firstSteps.mul(array2));
int[] array3 = {1, 2, 0};
assertEquals(0, firstSteps.mul(array3));
int[] array4 = {};
assertEquals(0, firstSteps.mul(array4));
}
``````

``````public void testSumArray() {
FirstSteps firstSteps = new FirstSteps();
int[] array1 = {1, 2, 3};
assertEquals(6, firstSteps.sum(array1));
int[] array2 = {-1, -2, 3};
assertEquals(0, firstSteps.sum(array2));
int[] array3 = {};
assertEquals(0, firstSteps.sum(array3));
}
``````

``````public class FirstSteps {
public int sum(int[] array){
int sum = 0;
for (int value : array) {
sum += value;
}
return sum;
}
}
``````

``````public class FirstSteps {
public int mul(int[] array){
int mul = 1;  // 注意这里初始化为1，而不是0
for (int value : array) {
mul *= value;
}
return mul;
}
}
``````

I need code that multiplies array contents which are formed by test

``````public void testMulArray() {
FirstSteps firstSteps = new FirstSteps();
int[] array1 = {1, 2, 3};
assertEquals(6, firstSteps.mul(array1));
int[] array2 = {-1, -2, 3};
assertEquals(6, firstSteps.mul(array2));
int[] array3 = {1, 2, 0};
assertEquals(0, firstSteps.mul(array3));
int[] array4 = {};
assertEquals(0, firstSteps.mul(array4));
}
``````

Before this, I made a similar code that returns the sum of array contents that is formed by the test

``````public void testSumArray() {
FirstSteps firstSteps = new FirstSteps();
int[] array1 = {1, 2, 3};
assertEquals(6, firstSteps.sum(array1));
int[] array2 = {-1, -2, 3};
assertEquals(0, firstSteps.sum(array2));
int[] array3 = {};
assertEquals(0, firstSteps.sum(array3));
}
``````

Code for sum is

``````public class FirstSteps {
public int sum(int[] array){
int sum = 0;
for (int value : array) {
sum += value;
}
return sum;
}
}
``````

It worked and for multiplying I made similar code

``````public class FirstSteps {
public int mul(int[] array){
int mul = 0;
for (int value : array) {
mul *= value;
}
return mul;
}
}
``````

# 答案1

``````public class FirstSteps {
public int mul(int[] array){
if (array.length == 0) return 0;
int mul = 1;
for (int value : array) {
mul *= value;
}
return mul;
}
}
``````

You make `mul = 0`, but, zero multiplies by any number results zero!

Instead you should make that initial value `mul = 1`.

``````public class FirstSteps {
public int mul(int[] array){
if (array.length == 0) return 0;
int mul = 1;
for (int value : array) {
mul *= value;
}
return mul;
}
}
``````

• 本文由 发表于 2020年8月3日 17:50:19
• 转载请务必保留本文链接：https://go.coder-hub.com/63227200.html
• arrays
• java

go 32

go 29

go 37

go 42