跳到主要内容

Math and Numerics

Short, interview-ready summary of common math in C#.


Memory hook

"Math = static helpers for numbers; MathF for float; Math.Clamp / Min / Max for bounds"


Math (double)

Math.Abs(-5); // 5
Math.Ceiling(3.2); // 4
Math.Floor(3.8); // 3
Math.Round(3.5); // 4 (banker's rounding by default)
Math.Round(3.5, 1); // 3.5 (1 decimal)
Math.Truncate(3.8); // 3 (drop fractional part)

Math.Min(1, 2); // 1
Math.Max(1, 2); // 2
Math.Clamp(10, 0, 5); // 5 (value, min, max)

Math.Sqrt(16); // 4
Math.Pow(2, 3); // 8
Math.Sign(-3); // -1

MathF (float)

  • Same methods as Math but for float (e.g. MathF.Abs, MathF.Sqrt)
  • Use when working with float to avoid extra conversions

Rounding modes

Math.Round(3.5); // MidpointRounding.ToEven (default)
Math.Round(3.5, MidpointRounding.AwayFromZero); // 4
  • ToEven — banker’s rounding; 2.5 → 2, 3.5 → 4
  • AwayFromZero — 2.5 → 3, 3.5 → 4

Integer division and remainder

int q = 10 / 3;   // 3 (integer division)
int r = 10 % 3; // 1 (remainder)
  • decimal division: 10.0m / 3 or (decimal)10 / 3

Random

// .NET 6+
int n = Random.Shared.Next(); // 0 to int.MaxValue-1
int n2 = Random.Shared.Next(10); // 0..9
int n3 = Random.Shared.Next(1, 11); // 1..10
double d = Random.Shared.NextDouble(); // 0.0..1.0
  • Random.Shared — thread-safe shared instance
  • For full control: new Random() or new Random(seed)

Interview one-liner

"Math provides static methods for Abs, Round, Floor, Ceiling, Min, Max, Clamp, Sqrt, Pow. Use MathF for float. Round uses banker’s rounding by default; use MidpointRounding for other behavior. Use Random.Shared for simple thread-safe random numbers."


Cheat sheet

Math.Abs, Round, Floor, Ceiling, Truncate
Math.Min, Max, Clamp
Math.Sqrt, Pow, Sign
MathF = float version
Random.Shared.Next(), NextDouble()