es036a_06_ArithConversion_4.ppt

advertisement
ES 036
Programming
Fundamentals
Arithmetic Conversion
QRAHMAN@eng.uwo.ca
TEB 361
519-661-2111 x81399
Dr. Quazi M. Rahman
Arithmetic conversions
Implicit Conversion
 Explicit Conversion

16-Jul-1
ES036 QMR / RE
2
Implicit Conversion (IC)
IC results inherent promotion of an
operand with a lower (in terms of memory
space) data type to the data-type of the
other operand in the presence of an
arithmetic (binary) operator.
 Implicit arithmetic conversion is also called
automatic conversion, implicit conversion,
coercion, promotion or widening.
 Ex: int a, float b; (a + b) will be a float type
where int a gets promoted to float a.

16-Jul-1
ES036 QMR / RE
3
Explicit Conversions: Cast
Explicit arithmetic conversions are called
casts. For example, int a can be explicitly
converted to a float variable by the
declaration (float) a.
 Cast operator: (data_type) variable
 Cast operator is an unary operator
 Examples:

 (double)
2
 X = (float) ((int) y+4)
 (double) (x = 10);
ES036 QMR / RE
16-Jul-1
4
Cast

Example: casting is integer division.
Suppose that 5 kids were asked how
many apples they ate, and the answers
were summed (12).
Average?
16-Jul-1
ES036 QMR / RE
5
Casting
#include <iostream>
using namespace std;
int main(void)
{
int total_apples = 12, kids = 5;
float apples_per_kid;
apples_per_kid = total_apples / kids;
cout<<“Average is ", apples_per_kid;
return 0;
}
16-Jul-1
ES036 QMR / RE
6
Casting
The output is
Average is 2




The reason that the output is not accurate can be traced
back to the statement
apples_per_kid = total_apples / kids
Division has higher precedence than the assignment
operator so it is done first.
Integer division truncates the fractional part of the
answer so 12/5 = 2
The assignment operator automatically converts the
integer 2 to float
16-Jul-1
ES036 QMR / RE
7
Casting
To fix the problem, one of the variable in the
division is temporarily converted to a float.
apples_per_kid = (float)total_apples / kids;
or
apples_per_kid = total_apples / (float)kids;


Note that it makes sense that the variables
total_apples and kids are ints because they have
to be whole numbers.
16-Jul-1
ES036 QMR / RE
8
Download