Monday, July 29, 2013

Math

Modulus is useful in that you can keep things from going over a certain threshold 

            const int maxDegrees = 360;
            int angle = 365; //Doesn't exist on a 2D scale
            int finalOutput;

            finalOutput = angle % maxDegrees;
//Instead of continuing past the set threshold, the value will loop clocklike

            Console.WriteLine("Angle is equal to " + finalOutput);
            Console.Read();

        
This will echo back 5 instead of 365

C# will truncate any decimals values. If you want to round off, use:


int x = 3; Math.Round //Simple Round
int x = 3; Math.Floor //Round down
int x = 3; Math.Ceiling  //Round Up

Typecasting:


int x = 10;
float y = 3;
______________________________________________________________
finalValue = x / y; //This doesn't work the way you'd want it to because C# will upgrade the integer to float.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

finalValue = x / (int)y; //This will temporarily unfloat the Y value

or 

finalValue = (int)(x / y); //This also "works" kind of, but the returned value will be a little off.

No comments:

Post a Comment