
Performing Calculations
137
Operands and Operators
One issue that confuses some people is the fact that C# uses the data types of an expression’s operands
to determine the way the operators work. If an expression contains two integers, the operators use
integer arithmetic. If an expression contains two floats, the operators use floating-point arithmetic.
Sometimes this can lead to confusing results. For example, the following code tries to save the
value 1/7 in the
float variable ratio. The values 1 and 7 are integers so this calculation uses
integer division, which discards any remainder. Because 1 / 7 = 0 with a remainder of 1,
ratio is
assigned the value 0, which is probably not what you intended.
float ratio = 1 / 7;
To force C# into using floating-point division, you can convert the numbers into the float data
type. The following code uses the
F suffix character to indicate that 1 and 7 should have the float
data type instead of
int. Now the program performs floating-point division so it assigns ratio the
value 0.142857149 (approximately).
float ratio = 1F / 7F;
Instead of using data type prefixes, you can also use casting to make the program treat the values as
floats as in the following code:
float ratio = (float)1 / (float)7;
Promotion
If an expression uses two different data types, C# promotes the one with the more restrictive type.
For example, if you try to divide an
int by a