Arithmetic Operators
Like in most languages, C# supports basic math operations using the following operators:
| Operator | Name | string with string | int with int | double with double | int with double |
|---|---|---|---|---|---|
+ | Addition | "H" + "i" → "Hi" | 3 + 2 → 5 | 3.2 + 2.5 → 5.7 | 3 + 2.0 → 5 |
- | Subtraction | Error ❌ | 3 - 2 → 1 | 3.2 - 2.5 → 0.7 | 3 - 2.0 → 1 |
* | Multiplication | Error ❌ | 3 * 2 → 6 | 3.5 * 2.0 → 7.0 | 3 * 2.0 → 6 |
/ | Division | Error ❌ | 3 / 2 → 1 | 3.0 / 2.0 → 1.5 | 3 / 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 double | Truncated to int |
|---|---|
45.9 | 45 |
45.0 | 45 |
45.1 | 45 |
-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.