C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Casts: In the first and third assignments, there were no casts on the integers or the entire division was cast at once.
DoubleTip: To coerce the intermediate language to have the correct casts, we cast either operand (number2 and number5) or both operands.
And: When either operand or both operands are cast to double, the output is approximately 0.29.
C# program that divides numbers
using System;
class Program
{
static void Main()
{
// 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);
}
}
Output
0
0.289855072463768
0
0.289855072463768
0.289855072463768
So: You can think of the 2 operands on each division expression as parameters to a method with a custom syntax.
Note: The complexity of this situation is mainly because of the rules by which the C# compiler interprets casts in the source code.
And: All the parameters will be promoted to match the signature. This is an algorithm the C# compiler uses to ensure more programs compile.