tags:

views:

71

answers:

3

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!

+1  A: 

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

ratio = map(ratio, function(x) { return abs(x); }); 

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:

for (int i=0;i<=10;i++){
    ratio = Math.abs(ratio[i]);
}

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:

function abs(int x){
    if (x < 0) return -x;
    return x;
} 
thedayturns
A: 

In pseudocode:

foreach value in the array:
    if array[value] < 0:
        array[value] = array[value] * -1

After this, every value in the array will be the absolute, non-negative value.

Noel M
so, such multiplication actually works huh? You sure?
esther
A: 

Your own code works fine, except for two details:

  • The for-loop should probably go from 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].
  • The if-statement, if(x[i]<1), should compare x[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).

Jakob