160 likes | 168 Views
Learn about different types of data conversions including assignment, arithmetic, and casting conversions. Understand the concepts of widening and narrowing conversions.
E N D
25 25 int byte 1289.0 1289 Widening Conversions double int
123456 123 byte int 123456.789 123456 double int Narrowing Conversions
SO WHAT? • Ariane 5 was a $500 million unmanned space craft designed by the European Space Agency • On June 4, 1996 it was launched for the first time • Here’s what happened “The failure occurred because the horizontal velocity exceeded the maximum value for a 16 bit unsigned integer when it was converted from it's signed 64 bit representation.” Source: http://www.vuw.ac.nz/staff/stephen_marshall/SE/Failures/SE_Ariane.html
Conversions can occur in three ways • Assignment conversion • Arithmetic conversion • Casting
memory x 1234 y ? Assignment conversion int x = 1234; double y; y = x; Only widening conversions can happen via assignment 1234.0
Arithmetic conversion 15.0 15 4.0 / int gets promoted to a double 3.5 Operands are always promoted to the “wider” type
memory x ? y 12345.67 Casting int x; double y = 12345.67; x = (int) y; 12345 Type is put in parentheses in front of value being converted avg = (double) sum / count; Common use is when we are dividing two ints but want a floating point result
Casting Practice • (double) 10 / 4 • (double) (10 / 4) • (int) ((double) 10 / (double) 4 ) + 1.0
Casting Practice (double) 10 / 4 casting 10.0 / 4 arithmetic promotion 10.0 / 4.0 double division 2.5
Casting Practice (double) (10 / 4) int division (double) 2 casting 2.0
Casting Practice (int) ((double) 10 / (double) 4 ) + 1.0 casting (int) ( 10.0 / 4.0 ) + 1.0 double division (int) 2.5 + 1.0 casting 2 + 1.0 arithmetic promotion 2.0 + 1.0 double addition 3.0
3.0 So what? double gpa; int totalPoints = 114, totalHours = 30; gpa = totalPoints / totalHours; gpa =114 / 30 integer division gpa =3 assignment conversion Note: 114.0 / 30.0 = 3.8 Peer Instruction questions