C# Numbers & Math
C# provides several numeric types and a built-in Math class with useful methods for calculations, like finding the square root, rounding numbers, or finding the maximum of two values.
The Math class is part of the System namespace and provides static methods, meaning you call them directly on the class itself, like Math.Sqrt(9).
Math.Sqrt(x);
Math.Max(x, y);
Math.Round(x);The Math class
Math.Sqrt() finds a square root, Math.Pow() raises a number to a power, Math.Max()/Math.Min() find the larger/smaller of two values, and Math.Round() rounds a decimal number.
Random numbers
The Random class generates pseudo-random numbers, useful for games and simulations. Random.Next(min, max) returns a random integer within a range.
using System;
class Program {
static void Main() {
Console.WriteLine(Math.Sqrt(16));
Console.WriteLine(Math.Pow(2, 3));
}
}4
8Math.Sqrt() finds the square root and Math.Pow() raises 2 to the power of 3.
using System;
class Program {
static void Main() {
Random rnd = new Random();
int number = rnd.Next(1, 10);
Console.WriteLine(number >= 1 && number < 10);
}
}TrueRandom.Next(1, 10) returns a random integer between 1 (inclusive) and 10 (exclusive).
Key points
- The Math class provides static methods for common calculations.
- Math.Sqrt(), Math.Pow(), Math.Max() and Math.Min() are commonly used.
- Math.Round() rounds a number to the nearest whole number or decimal places.
- The Random class generates pseudo-random numbers.
