Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function to return a sign

Tags:

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
like image 723
Icemanind Avatar asked Jul 15 '10 20:07

Icemanind


2 Answers

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
// ....
like image 68
Reed Copsey Avatar answered Sep 19 '22 17:09

Reed Copsey


int sign = Math.Sign(number);

It already exists.

like image 29
Tesserex Avatar answered Sep 20 '22 17:09

Tesserex