C# ยท Chapter 14 of 46

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).

Syntax
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.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    Console.WriteLine(Math.Sqrt(16));
    Console.WriteLine(Math.Pow(2, 3));
  }
}
Output
4
8

Math.Sqrt() finds the square root and Math.Pow() raises 2 to the power of 3.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    Random rnd = new Random();
    int number = rnd.Next(1, 10);
    Console.WriteLine(number >= 1 && number < 10);
  }
}
Output
True

Random.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.
๐Ÿ’ก Note: Math.Round() uses 'banker's rounding' by default, rounding to the nearest even number for .5 values.

๐Ÿ“ Quick Quiz

1. Which method finds the square root of a number?

2. Which class generates random numbers?

3. What does Math.Max(3, 7) return?