In C# division uses the forward-slash character. With division, one common problem is related to correctly casting the operands in the division.
With correct syntax, we get a double
from the division of 2 ints. But if we do not cast an int
in the expression, the result may be truncated (and not useful for us).
Consider a number like 100. We want to divide it by 345, and we must get a fractional double
result. We must use a cast on the numerator (or denominator).
(double)100 / 345 = ... 100 / (double)345 = ...
This program declares 2 Int32
variables and then divides the first by the second in 5 different operations. The operations differ in lexical syntax.
double
, the output is approximately 0.29.using System; // Divide the first number by the second number. int operand1 = 100; int operand2 = 345; // Incorrect division for double: double number1 = operand1 / operand2; Console.WriteLine(number1); // Correct division for double: double number2 = (double)operand1 / operand2; Console.WriteLine(number2); // Incorrect division for double: double number3 = (double)(operand1 / operand2); Console.WriteLine(number3); // Correct division for double: double number4 = (double)operand1 / (double)operand2; Console.WriteLine(number4); // Correct division for double: double number5 = operand1 / (double)operand2; Console.WriteLine(number5);0 0.289855072463768 0 0.289855072463768 0.289855072463768
The C# language specification provides the definition of all its predefined operators. It describes these predefined operators in the same way as real methods.
In numeric promotion, a parameter to an operator or method can be implicitly converted to match the operator or method signature. The C# compiler does this to help more programs compile.
A modulo operator implements remainder division. This might remind you of doing long division in school, where you must compute the "left over" part after dividing 2 numbers.
We used the casting syntax in division to ensure the correct number of decimal places. You need to cast one or both operands to get a double
type.