Icemanind
Icemanind

Reputation: 48686

A function to return a sign

I know this will really turn out to be simple, but my brain is just not working. I need a function in C# that will return -1 if the integer passed to the function has a negative sign, return 1 if the integer has a positive sign and return 0 if the number passed is 0. So for example:

int Sign=SignFunction(-82); // Should return -1
int Sign2=SignFunction(197); // Should return 1
int Sign3=SignFunction(0);   // Should return 0

Upvotes: 23

Views: 16743

Answers (8)

Josh
Josh

Reputation: 1387

If Math.Sign did not exist, I would do this:

return x == 0 ? 0 : x / Math.Abs(x);

Upvotes: 1

Tesserex
Tesserex

Reputation: 17314

int sign = Math.Sign(number);

It already exists.

Upvotes: 7

Reed Copsey
Reed Copsey

Reputation: 564403

This is already in the framework. Just use Math.Sign...

int sign = Math.Sign(-82); // Should return -1
int sign2 = Math.Sign(197); // Should return 1
int sign3 = Math.Sign(0);   // Should return 0

In addition, it will work with:

int sign4 = Math.Sign(-5.2); // Double value, returns -1
int sign5 = Math.Sign(0.0m); // Decimal, returns 0
// ....

Upvotes: 46

Gregoire
Gregoire

Reputation: 24832

public int Sign(int number)
{
    if(number==0)
       return 0;
    return number/Math.Abs(number);
}

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126834

return input.CompareTo(0);

Upvotes: 3

Vivin Paliath
Vivin Paliath

Reputation: 95518

public int SignFunction(int number) {
  return (number > 0) ? 
             1 : (number < 0) ? 
                    -1 : number;
}

Upvotes: 2

&#181;Bio
&#181;Bio

Reputation: 10748

public int SignFunction( int input )
{
    if( input < 0 ) return -1;
    if( input > 0 ) return 1;
    return 0;
}

Upvotes: 3

Adam Lear
Adam Lear

Reputation: 38768

public int SignFunction(int number) 
{
    return number.CompareTo(0);
}

Upvotes: 3

Related Questions