英文:
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
得分: 0
你将 mul = 0
,但是,零乘以任何数都等于零!
相反,你应该将初始值设为 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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论