Next: Example Program: Temperature Conversion
Up: The Assignment statement
Previous: Examples of Arithmetic Expressions
The rules stated above mean that division of integers will always give
an integer result. If the correct float result is required, then the
compiler must be forced to generate code that evaluates the expression
as a float
. If either of the operands is a constant, then it
can be expressed as a floating point constant by appending a .0
to it, as we have seen. Thus assuming that n
is an
int
variable, 1/n
does not give the correct reciprocal
of n
except in the situation n=1
. To force the
expression to be evaluated as a floating point expression, use
1.0/n
.
This solves the problem when one of the operands is a constant, but to
force an expression involving two int
variables to be evaluated
as a float
expression, at least one of the variables must be
converted to float
. This can be done by using the
cast operation:
f = float(i)/float(n);The type
float
is used as an operator to give a floating point
representation of the variable or expression in brackets. Notice that
f = float(i/n);
will still evaluate the expression as an
int
and only convert it to float
after the integer
division has been performed.
Other types can be used to cast values too.
int(x)
will return the value of x
expressed as an
int
. Similarly, char(y)
will return the character
corresponding to the value y
in the ASCII character set.