Alex Rivera | Logout

A function to return a sign

Asked 2010-07-15T20:02:01.987
23

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
Edit
Report

1 Answer

1

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

return x == 0 ? 0 : x / Math.Abs(x);
answered 2010-07-15T20:34:52.727

Your Answer