Home

Math Function: Sign

     

TIntroduction

One of the primary rules to observe in C# is that, after declaring a variable, before using it, it must have been initialized. Here are examples of initializing variables:

   

using System;

class Program
{
    static int Main()
    {
        short   sNumber = 225;
        int     iNumber = -847779;
        double  dNumber = 9710.275D;
        decimal mNumber = 35292742.884295M;

        Console.WriteLine("Short Integer:      {0}", sNumber);
        Console.WriteLine("Integral Number:    {0}", iNumber);
        Console.WriteLine("Double-Precision:   {0}", dNumber);
        Console.WriteLine("Extended Precision: {0}", mNumber);
	
        return 0;
    }
}

This would produce:

Short Integer:      225
Integral Number:    -847779
Double-Precision:   9710.275
Extended Precision: 35292742.884295
Press any key to continue . . .

When initializing a variable using a constant, you decide whether it is negative, 0 or positive. This is referred to as its sign. If you are getting the value of a variable some other way, you may not know its sign. Although you can use comparison operators to find this out, the Math class provides a method to check it out for you.

To find out about the sign of a value or a numeric variable, you can call the Math.Sign() method. It is overloaded in various versions whose syntaxes are:

public static int Sign(sbyte   value);
public static int Sign(short   value);
public static int Sign(int     value);
public static int Sign(long    value);
public static int Sign(sbyte   value);
public static int Sign(double  value);
public static int Sign(decimal value);

When calling this method, pass the value or the variable you want to consider, as argument. The method returns:

  • -1 if the argument is negative
  • 0 if the argument is 0
  • 1 if the argument is positive

Here are examples of calling the method:

using System;

class Program
{
    static int Main()
    {
        short   sNumber = 225;
        int     iNumber = -847779;
        double  dNumber = 9710.275D;
        decimal mNumber = 35292742.884295M;

        Console.WriteLine("Number: {0} => Sign: {1}",
                          sNumber, Math.Sign(sNumber));
        Console.WriteLine("Number: {0} => Sign: {1}",
                          iNumber, Math.Sign(iNumber));
        Console.WriteLine("Number: {0} => Sign: {1}",
                          dNumber, Math.Sign(dNumber));
        Console.WriteLine("Number: {0} => Sign: {1}\n",
                          mNumber, Math.Sign(mNumber));
	
        return 0;
    }
}

This would produce:

Number: 225 => Sign: 1
Number: -847779 => Sign: -1
Number: 9710.275 => Sign: 1
Number: 35292742.884295 => Sign: 1

Press any key to continue . . .
 
 

Home Copyright © 2010-2016, FunctionX