Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find absolute value in C?

I need to lighten the code, and then eliminate the underlying if that check if the subtraction are <0 and if the condition is true I multiply * -1 in order to have subtraction >0 (absolute value).

I wonder if there is a function or some operator able to perform the calculation directly in absolute value?

int i,j,N,max,s,s1;
        s=v[i]-v[j];
        s1=i-j;
        if(s1<0){
            s1*=(-1);
        }
        if(s<0){
            s*=(-1);
        }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As the comments say:

s = abs(x - y)

The manpage for abs (and also labs, llabs): https://linux.die.net/man/3/abs

It looks like you’re doing this in a for loop of some sort (i,j are hopefully loop indices, otherwise you need to name your variables more descriptively). In that case, you should be able to architect it such that j is never greater than i for a performance increase.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading