Mathematical Operators

C# uses five mathematical operators, four for standard calculations and one to return the remainder when dividing integers. The following sections consider the use of these operators.

Simple Arithmetical Operators (+, -, *, / )

C# offers operators for simple arithmetic: the addition (+), subtraction (-), multiplication (*), and division (/) operators work as you might expect, with the possible exception of integer division.

When you divide two integers, C# divides like a child in the fourth grade: it throws away any fractional remainder. Thus, dividing 17 by 4 returns a value of 4 (17/4 = 4, with C# discarding the remainder of 1).

This limitation is specific to integer division. If you do not want the fractional part thrown away, you can use one of the types that support decimal values, such as float and double. Division between two floats (using the / operator) returns a fractional answer. Integer and fractional division is illustrated in Example 7-1.

Example 7-1. Integer and float division

using System;
public class Tester
{
    public static void Main()
    {
        int smallInt = 5;
        int largeInt = 12;
        int intQuotient;
        intQuotient = largeInt / smallInt;
        Console.WriteLine("Dividing integers. {0} / {1} = {2}",
            largeInt, smallInt, intQuotient);

        float smallFloat = 5;
        float largeFloat = 12;
        float FloatQuotient;
        FloatQuotient = largeFloat / smallFloat;
        Console.WriteLine("Dividing floats. {0} / {1} = {2}",
            largeFloat, smallFloat, FloatQuotient);

    }
}
Output: Dividing ...

Get Learning C# now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.