O'Reilly logo

Learning C# by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required