Numbers in C#

Explore integer math

int a = 18;
int b = 6;

// Addition
int c = a + b;
Console.WriteLine(c); // 24

// Subtraction
c = a - b;
Console.WriteLine(c); // 12

// Multiplication
c = a * b;
Console.WriteLine(c); // 108

// Division
c = a / b;
Console.WriteLine(c); // 3

Explore order of operations

// Multiplication/division is higher than addition/subtraction
int a = 5;
int b = 4;
int c = 2;
int d = a + b * c;
Console.WriteLine(d); // 13

// Parentheses
d = (a + b) * c;
Console.WriteLine(d); // 18

// Integer division produces an integer result
d = (a + b) / c;
Console.WriteLine(d); // 4

Explore integer precision and limits

// Remainder (modulo)
int a = 7;
int b = 4;
int c = 3;
int d = (a + b) / c;
int e = (a + b) % c;
Console.WriteLine($"quotient: {d}");
Console.WriteLine($"remainder: {e}");

// int range
int max = int.MaxValue;
int min = int.MinValue;
Console.WriteLine($"The range of integers is {min} to {max}");

// integer overflow
int what = max + 3;
Console.WriteLine($"An example of overflow: {what}");

Work with the double type

// double division
double a = 5;
double b = 4;
double c = 2;
double d = (a + b) / c;
Console.WriteLine(d);

// double range
double max = double.MaxValue;
double min = double.MinValue;
Console.WriteLine($"The range of double is {min} to {max}");

// Rounding error
double third = 1.0 / 3.0;
Console.WriteLine(third);

Work with decimal types

// decimal range
decimal min = decimal.MinValue;
decimal max = decimal.MaxValue;
Console.WriteLine($"The range of the decimal type is {min} to {max}");
// The range of the decimal type is -79228162514264337593543950335 to 79228162514264337593543950335

// double
double a = 1.0;
double b = 3.0;
Console.WriteLine(a / b); // 0.333333333333333

// decimal
// Must end with "M", otherwise the compiler assumes double
decimal c = 1.0M;
decimal d = 3.0M;
Console.WriteLine(c / d); // 0.3333333333333333333333333333

// Calculate the area of a circle whose radius is 2.50 centimeters
double r = 2.50;
double area = Math.PI * r * r;
Console.WriteLine($"The area is {area}"); // The area is 19.6349540849362

Last updated