java 使用增强循环乘以数组的所有值?爪哇

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15466246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:42:04  来源:igfitidea点击:

Multiplying all values of an array using an enhanced loop? Java

javaarrays

提问by Nicholas Vera

The title pretty much covers it. For some reason this problem is escaping me and I can't find the logical answer to this.

标题几乎涵盖了它。出于某种原因,这个问题正在逃避我,我找不到合乎逻辑的答案。

EDIT:

编辑:

Say I have

说我有

int[] values = (2,5,3,2,1,4,6,3,2,1,5,3)

I want to get the product of multiplying all these elements. My textbook asks to do this with an enhanced for loop.

我想得到所有这些元素相乘的结果。我的教科书要求使用增强的 for 循环来做到这一点。

for (int element : values)
{
NO CLUE WHAT TO PUT HERE
}

My first guess, however, was that it couldn't be done with an enhanced for loop.

然而,我的第一个猜测是它无法通过增强的 for 循环来完成。

Is my textbook just trying to trick me to teach me some sort of lesson?

我的教科书只是试图欺骗我教我某种课程吗?

回答by Maroun

This can't be done with enhanced for loop. Assume you have an array: (I updated the answer after the OP has updated the question, the update is below).

使用增强的 for 循环无法做到这一点。假设您有一个数组:(我在 OP 更新问题后更新了答案,更新如下)。

int[] a = {1,2,3};

int[] a = {1,2,3};

When you do:

当你这样做时:

for(int num : a) {
  num = num*something;
} 

You are actually multiplying another variable(the array won't be affected)..

您实际上是在乘以另一个变量(数组不会受到影响)。

numin the above example is only a copy of an array element. So actually you are modifying a local variable, not the array itself.

num在上面的例子中只是一个数组元素的副本。所以实际上你正在修改一个局部变量,而不是数组本身。

Read thisand you'll see that the value in the array is copied into a local variable, and this local variable is used. So this multiplication will not affect the original values of the arrays.

阅读本文,您将看到数组中的值被复制到一个局部变量中,并使用了该局部变量。所以这个乘法不会影响数组的原始值。



OP UPDATE:

操作更新

If you want to multiply elements and get the result, you can. Your text book is not trying to trick you. It doesn't ask you to changethe values. But to use them in order to do some calculations:

如果你想将元素相乘并得到结果,你可以. 你的教科书并没有试图欺骗你。它不会要求您更改这些值。但是要使用它们来进行一些计算:

int[] values = {2,5,3,2,1,4,6,3,2,1,5,3};
int result=1;
for(int value : values) {
    result *= value;
} 
System.out.println("The result: " + result); //Will print the result of 2*5*3*2*...

回答by Glen Best

This can easily be done with an enhanced for loop:

这可以通过增强的 for 循环轻松完成:

int result = 1;
for (int element : values)
{
    result *= element;
}

回答by user7530344

int index = 0;
for (int element : values)
{

    values[index] = element + someVariable;
    index++;
}

回答by Chris Cooper

It can't be done, you will have to use old-style array addressing:

这是不可能的,您将不得不使用旧式数组寻址:

for (int i = 0; i < array.length; i++) {
  array[i] = array[i] * 2;
}