【问题标题】:Method that returns the product of elements in an integer array [duplicate]返回整数数组中元素乘积的方法[重复]
【发布时间】:2014-12-08 08:58:25
【问题描述】:

我被卡住了,如果有人能指出我正确的方向,那就太好了。我在下面有这段代码,我需要添加一个返回数组中元素乘积的方法。

public class ArrayProduct
{
  public static void main( String [] args )
  {
    int [] intArray = { 1, 2, 3, 4, 5, 6 };

    System.out.print( "The elements are " );
    for ( int i = 0; i < intArray.length; i++ )
       System.out.print( intArray[i] + " " );
    System.out.println( );

    System.out.println( "The product of all elements in the array is "
                         + arrayProduct( intArray ) );
  }

  // Insert your code here

}

我只是不确定在不完全更改代码的情况下解决此问题的方法!

【问题讨论】:

  • Q.1 你会如何用笔和纸来做这件事?
  • 提示:看看如何在 Java 中迭代数组,然后进行数学运算。就这么简单
  • 这绝对不是链接问题的重复。

标签: java arrays methods product


【解决方案1】:
public static int arrayProduct(int[] array){
    int rtn=1;
    for(int i: array){
        rtn*=i;
    }
    return rtn;
}

【讨论】:

  • 感谢您的帮助!我错过了方法头!
【解决方案2】:

您需要一个新变量来存储结果。这个变量必须用中性整数初始化才能进行乘法运算。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    相关资源
    最近更新 更多