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 Arithmetic Operators (+, –, *, /)
C# offers four operators for simple arithmetic: the addition (+), subtraction (–), multiplication (*), and division (/) operators. The + and – operators are obvious, and work as you might expect. The * operator for multiplication may look a bit odd if you’re not used to it, but there’s nothing else special about it. Division, however, is slightly unusual, depending on the types you’re dividing.
When you divide two integers, C# divides like a child in the third grade: it throws away any fractional remainder. Thus, dividing 17 by 4 returns a value of 4 (C# discards 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 or double. Division between two floats (using the / operator) returns a decimal answer. Integer and floating-point division is illustrated in Example 4-1.
Example 4-1. Integer division is different from float division; in integer division, C# discards the remainder
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example_4_1_ _ _ _Integer_and_Float_Division { class Program { public static void Main( ) { int smallInt = 5; int largeInt = 12; int intQuotient; ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access