Skip to main content

Arithmetic Operators

Like in most languages, C# supports basic math operations using the following operators:

OperatorNamestring with stringint with intdouble with doubleint with double
+Addition"H" + "i" → "Hi"3 + 2 → 53.2 + 2.5 → 5.73 + 2.0 → 5
-SubtractionError ❌3 - 2 → 13.2 - 2.5 → 0.73 - 2.0 → 1
*MultiplicationError ❌3 * 2 → 63.5 * 2.0 → 7.03 * 2.0 → 6
/DivisionError ❌3 / 2 → 13.0 / 2.0 → 1.53 / 2.0 → 1.5

Integer Truncation​

Dividing two integers can produce unexpected results when the result isn't a whole number:

int a = 1;
int b = 2;

int half = a / b;
Console.WriteLine($"One divided by two is: {half}"); // Output: 0

You might expect 0.5, but the result is 0 >:^(

This happens because int can't store decimal places, so any fractional part is discarded. This is a behavior known as truncation.

Positive vs Negative Examples​

Truncation always moves the value toward zero, regardless of sign:

Original doubleTruncated to int
45.945
45.045
45.145
-45.1-45
-45.0-45
-45.9-45

References​

Bultena, Sandra and Youmna Badawy. "Integers & Floats." 420-SN1 Notes, John Abbott College, john-abbott-college.github.io/SN1-Notes/topics/04_variables/03_integers_floats/03_integers_floats.html

Buschinelli, Mauricio. "420-1P6 - Week 4" John Abbott College, Fall 2023.