Download presentation
Presentation is loading. Please wait.
Published byBlaze Price Modified over 8 years ago
1
CSCI 125 & 161 / ENGR 144 Lecture 6 Martin van Bommel
2
Automatic Type Conversion Value of one type converted to another type as implicit part of computation 2 + 3.5 is 5.5 Integer 2 is converted into float 2.0 Assume variable total is of type double total = 0; Integer 0 converted to double 0.0
3
Truncation Automatic type conversion of double to integer drops any decimal fraction Assume variable n is of type int n = 1.99; Result is value of n is set to 1
4
Example of Truncation Write a program to convert a given number of centimeters to the equivalent in feet and inches Program “cmtofeet.cpp”
5
Explicit Type Conversion Type cast - unary operator to convert value Desired type in parenthesis before value e.g. average = sum / count; If sum and count are integers, would perform integer division for average average = (double) sum / count;
6
Shorthand Assignment Can replace variable = variable op expression; by variable op= expression; e.g. sum += value; counter += 1; value /= 10;
7
Incrementing and Decrementing Further shorthands for: –incrementing - adding 1 to a variable variable++; –decrementing - subtracting 1 from variable variable --; e.g. counter++;
8
Output cout used to display integers, real numbers (floats and doubles), characters, and strings cout << exp 1 << exp 2 … ; cout << ”Measurement is ”; cout << (inches / 12) << ” ft ”; cout << (inches % 12) << ” in”;
9
I/O Manipulation has parameterized manipulators to modify behavior of cout Format: cout << manipulator(parameter); Examples: –setw – sets minimum field width for value –setprecision – sets number of significant digits cout << setw(5) << setprecision(2) << 1.53; outputs: | 1.5|
10
May wish for setprecision to specify number of digits after decimal Can use the manipulator fixed cout << setprecision(2) << fixed;
11
Manipulators FlagUsage fixed fixed-point notation scientific scientific notation showpoint show decimal (even if.0) left left-adjust output right right-adjust output setw(n) width of print field setprecision(n) number of digits
12
Formatted Output Need to align numbers in columns NameNumberSalary Joe 123 94.56 Joan 2340125.38 cout << setprecision(2) << fixed; cout << setw(8) << left << name << right; cout << setw(4) << num << setw(8) << salary << endl;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.