[英]Need code that multiplies arrays, and returns 0 if array is empty
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;
}
}
You make mul = 0
, but, zero multiplies by any number results zero!您使mul = 0
,但是,零乘以任何数字结果为零!
Instead you should make that initial value mul = 1
.相反,您应该使初始值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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.