如何将整数与数组中的值相乘?
实际上,我想从数组中获取绝对值,这是我能想到的使用“if”循环将数组中的值与(-1)相乘的唯一方法。但真的是这样吗?如:
for (i = 1 ; i <= 10 ; i++) {
if(x[i]<1) {
x[i] = (-1) * x[i];
} else{}
ratio[i] = (x[i]/fx[i]) * 0.5;
}
我不确定你是否可以将一个整数与一个数组相乘..或者至少,当我执行上述操作时,它没有产生我想要的结果,负数仍然存在..
并且我意识到这个表达式如果(x[i]<1) 不起作用,希望有人能帮忙!真的很感激~ 如果没有,还有其他办法吗?谢谢!
Actually I wanted to get absolute values out of an array and the only way i can think of multiplying the values in the array with (-1) using 'if' loop. But does it work like that? as in:
for (i = 1 ; i <= 10 ; i++) {
if(x[i]<1) {
x[i] = (-1) * x[i];
} else{}
ratio[i] = (x[i]/fx[i]) * 0.5;
}
I am not sure if u can just multiply an integer with an array..or at least, when i do the aboive it didnt produce the results i want, the negatives are still there..
And i realized that this expression if(x[i]<1) does not work, hope someone can help! really appreciate it~
If not, is there another way? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这里了解您使用的语言非常重要。
如果您使用的语言中包含函数式编程,您可以执行以下操作(伪代码):
Map 将函数应用于每个参数,并从所有结果中创建一个新数组。
如果您没有地图,那么类似这样的事情应该可以正常工作:
Math.abs 被假定为计算绝对值的库函数。 Math.abs 的确切位置取决于语言;例如,在 C++ 中,它在 cmath 中。
如果你找不到它,你可以这样写:
What language you're using is very important to know here.
If you are using a language with pieces of functional programming in it, you could do something like this (psuedocode):
Map applies the function to each argument, and makes a new array out of all of the results.
If you don't have map, then something like this should work fine:
Math.abs is assumed to be a library function to compute absolute value. The exact location of Math.abs is dependent on language; in c++ it's in cmath, for instance.
If you can't find it, you can always write it like this:
您自己的代码工作正常,除了两个细节:
0 到 9,而不是 1 到 10。至少如果语言是 C(或大多数语言)。乍一看可能很奇怪,但数组从 0 开始计数。因此第十个元素将被称为
x[9]
。if(x[i]<1)
应该将x[i]
与 0 而不是 1 进行比较,如下所示:if( x[i]<0)
。否则,您会将 0.5 之类的值转换为 -0.5。这应该能让它发挥作用。
作为一个小小的奖励,您可能还想完全删除
else{}
。它不做任何事情,没有它程序也能正常工作(同样,如果它是 C 或大多数其他语言)。Your own code works fine, except for two details:
0 to 9, not 1 to 10. At least if the langauge is C (or the majority of languages out there). Might seem strange at first, but arrays start counting from 0. Hence the tenth element will be referred to as
x[9]
.if(x[i]<1)
, should comparex[i]
to 0 instead of 1, like this:if(x[i]<0)
. Otherwise you'll turn values like 0.5 into -0.5.That should make it work.
As a little bonus, you might also want to remove
else{}
altogether. It doesn't do anything and the program will work fine without it (again, if it's C or most other languages).用伪代码表示:
在此之后,数组中的每个值都将是绝对的非负值。
In pseudocode:
After this, every value in the array will be the absolute, non-negative value.