1 / 16

Conversions & Casting

Learn about different types of data conversions including assignment, arithmetic, and casting conversions. Understand the concepts of widening and narrowing conversions.

jsalinas
Download Presentation

Conversions & Casting

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Conversions & Casting

  2. Data Conversions

  3. 25 25 int byte 1289.0 1289 Widening Conversions double int

  4. 123456 123 byte int 123456.789 123456 double int Narrowing Conversions

  5. 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

  6. Conversions can occur in three ways • Assignment conversion • Arithmetic conversion • Casting

  7. memory x 1234 y ? Assignment conversion int x = 1234; double y; y = x; Only widening conversions can happen via assignment 1234.0

  8. Arithmetic conversion 15.0 15 4.0 / int gets promoted to a double 3.5 Operands are always promoted to the “wider” type

  9. 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

  10. Casting Practice • (double) 10 / 4 • (double) (10 / 4) • (int) ((double) 10 / (double) 4 ) + 1.0

  11. Casting Practice (double) 10 / 4 casting 10.0 / 4 arithmetic promotion 10.0 / 4.0 double division 2.5

  12. Casting Practice (double) (10 / 4) int division (double) 2 casting 2.0

  13. 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

  14. So what?

  15. 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

  16. Pair Practice

More Related