Luka Peric
Luka Peric

Reputation: 1

How to set multiple numbers to their absolute value in C more concisely?

How can I simplify those three simple if conditions?

if(v.x < 0)
{
    v.x *= -1;
}
if(v.y < 0)
{
    v.y *= -1;
}
if(v.z < 0)
{
    v.z *= -1;
}

Upvotes: 0

Views: 718

Answers (2)

Magix
Magix

Reputation: 5339

You can do something like this :

v.x = (v.x < 0) ? (v.x * -1) : (v.x) ;
v.y = (v.y < 0) ? (v.y * -1) : (v.y) ;
v.z = (v.z < 0) ? (v.z * -1) : (v.z) ;

This uses the C ternary operator.

Upvotes: 1

mikedu95
mikedu95

Reputation: 1736

#include <stdlib.h>
...
v.x = abs(v.x);
v.y = abs(v.y);
v.z = abs(v.z);

Or labs, llabs, fabs (<math.h>), etc. depending of type of your numbers.

Upvotes: 11

Related Questions