使用增强循环将数组的所有值相乘?爪哇 [英] Multiplying all values of an array using an enhanced loop? Java

查看:61
本文介绍了使用增强循环将数组的所有值相乘?爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎涵盖了它.由于某种原因,这个问题使我无法逃脱,而我找不到对此的合乎逻辑的答案.

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

说我有

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

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

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

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

但是,我的第一个猜测是无法使用增强的for循环来完成.

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

我的教科书是否只是在试图欺骗我来教我一些课程?

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

推荐答案

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

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).

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

当您这样做:

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

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

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

num只是数组元素的副本.因此,实际上您是在修改局部变量,而不是数组本身.

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

阅读 ,您会看到数组中的值被复制到局部变量中,并且使用了该局部变量.因此,这种乘法不会影响数组的原始值.

Read this and 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更新:

如果要乘以元素并得到结果,可以可以.您的教科书并不是要欺骗您.它不会要求您更改值.但是要使用它们进行一些计算:

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 change the 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*...

这篇关于使用增强循环将数组的所有值相乘?爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆