[英]Need help in arrays product output
Consider the following Accumulator class with a missing method 考虑以下缺少方法的Accumulator类
'prodA(int m)' 'prodA(int m)'
which is supposed to return the product of all elements of the array A
if such product is less than or equal to m and return m otherwise. 如果该乘积小于或等于m,则应返回数组
A
所有元素的乘积,否则返回m。
For example if A is the array {2,4,3}
then 例如,如果A是数组
{2,4,3}
则
prodA(2) will return 2
prodA(0) will return 0
prodA(50) will return 24
(Hint: the length of an array A
is given by A.length
) (提示:数组
A
的长度由A.length
给出)
Insert the code for the body of the method prodA
where marked. 在标记处插入
prodA
方法主体的代码。
public class Accumulator {
private int[] A;
public Accumulator(int[] X) {
A= new int[X.length];
for (int i=0; i<X.length; i++)
A[i] = X[i];
}
public int prodA(int m) {
// insert your code here
}
}
You simply multiply the elements of the array A
, then check if the sum is smaller than m
, if so, you return it, otherwise you return m
. 您只需将数组
A
的元素相乘,然后检查总和是否小于m
,如果是,则返回它,否则返回m
。
I won't show you a full solution, but computing the multiplication of the elements is extremely easy, you should have an int res = 1;
我不会向您展示完整的解决方案,但是计算元素的乘法非常简单,您应该将
int res = 1;
and then multiply it by each element from the array and reassign the result to res
(using a loop). 然后将其乘以数组中的每个元素,然后将结果重新分配给
res
(使用循环)。
int prod=1;
for(int i:A){
prod=prod*i;
}
if(prod<m)
return prod;
else
return m;
public int prodA(int m) {
int p=1;
for(int i=0;i<A.lenght.i++){
p=p*A[i];
}
if(p<=m)
return p;
else
return m;
}
int product=1;
for(int num:A) {
product=product*num;
}
return (product<=m)?product:m;
There are not many things to consider here, but three come to my mind: 这里没有太多要考虑的事情,但我想到三件事:
return Math.min(limit, product(A))
with an appropriate product
method that only has the single responsibility of computing a product of the elements of an array. product
方法将乘积计算和实际结果的计算分开,例如return Math.min(limit, product(A))
,该方法只负责计算元素的乘积。数组。 However, this makes the "early return" impossible. The "early return" could do something like this: “提早归还”可以这样做:
public int prodA(int m)
{
int product = 1;
for (int i = 0; i < A.length; i++)
{
product *= A[i];
if (product >= m)
{
return m;
}
}
return product;
}
while from a standpoint of reusability, something like this might be nicer: 从可重用性的角度来看,类似以下的内容可能会更好:
public int prodA(int m)
{
return Math.min(m, product(A));
}
private static int product(int array[] )
{
int product = 1;
for (int i = 1; i < array.length; i++)
{
product *= array[i];
}
return product;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.