提问者:小点点

数组产品输出需要帮助


考虑以下带有一个缺失方法的累加器类

'prodA(int m)'

如果乘积小于或等于m,则返回数组< code>A的所有元素的乘积,否则返回m。

例如,如果A是数组< code>{2,4,3},则

prodA(2) will return 2
prodA(0) will return 0
prodA(50) will return 24

(提示:数组< code>A的长度由< code>A.length给出)

在标记处插入方法体的代码。

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
    }

}

共3个答案

匿名用户

您只需将数组< code>A的元素相乘,然后检查总和是否小于< code>m,如果是,则返回它,否则返回< code>m。

我不会向你展示一个完整的解决方案,但计算元素的乘法非常容易,你应该有一个 int res = 1;然后将其乘以数组中的每个元素并将结果重新分配给 res(使用循环)。

匿名用户

int prod=1;
for(int i:A){
  prod=prod*i;
}
if(prod<m)
 return prod;
else
 return m;

匿名用户

int product=1;      
for(int num:A) {
           product=product*num;
        }
        return (product<=m)?product:m;