Как найти произведение элементов массива java

Почему мой код не работает?

Нужно создать массив, заполнить случайными числами от 1 до 10 и найти произведение всех этих чисел.

public static void main(String[] args) {
    int[] array = new int[10];

    for (int i = 0; i < array.length; i++) {
        array[i] = 1 + (int) (Math.random() * 11);
    }
    long p = array[0] * array[1] * array[2] * array[3] * array[4] * array[5] * array[6] * array[7] * array[8] * array[9];
    System.out.println(p);
}

aleksandr barakin's user avatar

задан 12 июл 2020 в 14:56

gunniq's user avatar

2

int p = 0; // !!! Не торопитесь. Подумайте.
...
  p = p * array[i];

Вы доводите счетчик внешего цикла i до array.length во внутреннем цикле. Зачем тут вложенные циклы?


public static void main(String[] args) {
  int[] array = new int[10];
  int p = 1;
  for (int i = 0; i < array.length; i++) {
    array[i] = (int) (Math.random() * 10);
    p = p * array[i];
  }
  System.out.println(p);
}

ответ дан 12 июл 2020 в 14:59

14

To find the product of elements of an array.

  • create an empty variable. (product)
  • Initialize it with 1.
  • In a loop traverse through each element (or get each element from user) multiply each element to product.
  • Print the product.

Example

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class ProductOfArrayOfElements {
   public static void main(String args[]){
      System.out.println("Enter the required size of the array :: ");
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int myArray[] = new int [size];
      int product = 1;
      System.out.println("Enter the elements of the array one by one ");
      for(int i=0; i<size; i++){
         myArray[i] = s.nextInt();
         product = product * myArray[i];
      }
      System.out.println("Elements of the array are: "+Arrays.toString(myArray));
      System.out.println("Sum of the elements of the array ::"+product);
   }
}

Output

Enter the required size of the array:
5
Enter the elements of the array one by one
11
65
22
18
47
Elements of the array are: [11, 65, 22, 18, 47]
Sum of the elements of the array:13307580

I am stuck and if someone can point me in the right direction would be fantastic. I have this code below and I need to add a method that returns the product of elements in the array.

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

}

I’m just not sure of a way to solve this without completely changing the code all together!

asked Dec 8, 2014 at 8:58

PFKrang's user avatar

3

public static int arrayProduct(int[] array){
    int rtn=1;
    for(int i: array){
        rtn*=i;
    }
    return rtn;
}

answered Dec 8, 2014 at 9:11

Patrick Chan's user avatar

Patrick ChanPatrick Chan

1,01910 silver badges14 bronze badges

1

You need a new variable in which to store the result. This variable has to be initialized with the neutral integer for multiplication.

answered Dec 8, 2014 at 9:11

AdrianS's user avatar

AdrianSAdrianS

1,9507 gold badges33 silver badges51 bronze badges

0 / 0 / 0

Регистрация: 05.12.2018

Сообщений: 23

1

Произведение элементов массива

14.12.2018, 12:41. Показов 2511. Ответов 5


Студворк — интернет-сервис помощи студентам

Составьте программу вычисления произведения элементов, больших заданного числа Т, одномерного массива А(N), заполнив его случайным образом.(java)



0



Эксперт Java

3638 / 2970 / 918

Регистрация: 05.07.2013

Сообщений: 14,220

14.12.2018, 12:52

2

что непонятно?



0



2442 / 1898 / 475

Регистрация: 17.02.2014

Сообщений: 9,154

14.12.2018, 13:04

3



0



dmitryhad

1 / 0 / 1

Регистрация: 27.08.2015

Сообщений: 33

14.12.2018, 13:18

4

Лучший ответ Сообщение было отмечено Lprog как решение

Решение

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package cyberforum;
import java.util.Random;
import java.util.Scanner;
public class Main {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Random random = new Random();
        System.out.print("Введите длину массива: ");
        int n = sc.nextInt();
        int[] aa = new int[n];
        System.out.print("Введите число T: ");
        int t = sc.nextInt();
        
        for (int i = 0; i < aa.length; i++) {   //заполнение случайными числами до 50
            aa[i] = random.nextInt(50);
        }
        
        for (int i = 0; i < aa.length; i++) {   //Вывод массива
            System.out.println(aa[i]+" ");
        }
        
        long mult = 1;
        for (int i = 0; i < aa.length; i++) {   //произведение элемента на элемент при условии, что он больше T
            if (aa[i] > t) {
                mult = aa[i]*mult;
            } 
        }
        if (mult == 1) {
            System.out.println("Mult = 0 or (number > T) not found");
        }
        else {
            System.out.println("Mult = "+mult);
        }
    }
}



0



Am I evil? Yes, I am!

Эксперт PythonЭксперт Java

16117 / 9003 / 2605

Регистрация: 21.10.2017

Сообщений: 20,705

14.12.2018, 13:26

5

dmitryhad, вполне достаточно одного цикла.

Добавлено через 2 минуты
Или вообще без оного, да, Aviz__?



0



2442 / 1898 / 475

Регистрация: 17.02.2014

Сообщений: 9,154

14.12.2018, 14:46

6

Цитата
Сообщение от iSmokeJC
Посмотреть сообщение

Aviz__?

Да, блин, как только поймешь (или думаешь, что понял) принцип стримов, то так лень писать циклы



0



Порой обучение продвигается с трудом. Сложная теория, непонятные задания… Хочется бросить. Не сдавайтесь, все сложности можно преодолеть. Рассказываем, как

Не понятна формулировка, нашли опечатку?

Выделите текст, нажмите ctrl + enter и опишите проблему, затем отправьте нам. В течение нескольких дней мы улучшим формулировку или исправим опечатку

Что-то не получается в уроке?

Загляните в раздел «Обсуждение»:

  1. Изучите вопросы, которые задавали по уроку другие студенты — возможно, ответ на ваш уже есть
  2. Если вопросы остались, задайте свой. Расскажите, что непонятно или сложно, дайте ссылку на ваше решение. Обратите внимание — команда поддержки не отвечает на вопросы по коду, но поможет разобраться с заданием или выводом тестов
  3. Мы отвечаем на сообщения в течение 2-3 дней. К «Обсуждениям» могут подключаться и другие студенты. Возможно, получится решить вопрос быстрее!

Подробнее о том, как задавать вопросы по уроку

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти гадалку в новомосковске
  • Жесткий диск для компьютера как найти
  • Писк в микрофоне как исправить
  • Как найти налоговый номер на паспорте
  • Как найти какой интернет провайдер

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии