Transcript Class 6

CSCI 125 & 161 / ENGR 144
Lecture 6
Martin van Bommel
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
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
Example of Truncation
• Write a program to convert a given number
of centimeters to the equivalent in feet and
inches
• Program “cmtofeet.cpp”
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;
Shorthand Assignment
• Can replace
variable = variable op expression;
• by
variable op= expression;
• e.g. sum += value;
counter += 1;
value /= 10;
Incrementing and Decrementing
• Further shorthands for:
– incrementing - adding 1 to a variable
variable++;
– decrementing - subtracting 1 from variable
variable--;
• e.g.
counter++;
Output
• cout used to display integers, real numbers
(floats and doubles), characters, and strings
cout << exp1 << exp2 … ;
cout << ”Measurement is ”;
cout << (inches / 12) << ” ft ”;
cout << (inches % 12) << ” in”;
I/O Manipulation
• <iomanip> 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|
<iomanip>
• May wish for setprecision to specify number of
digits after decimal
• Can use the manipulator fixed
cout << setprecision(2) << fixed;
Manipulators
Flag
fixed
scientific
showpoint
left
right
setw(n)
setprecision(n)
Usage
fixed-point notation
scientific notation
show decimal (even if .0)
left-adjust output
right-adjust output
width of print field
number of digits
Formatted Output
• Need to align numbers in columns
Name
Joe
Joan
Number
123
2340
Salary
94.56
125.38
cout << setprecision(2) << fixed;
cout << setw(8) << left << name << right;
cout << setw(4) << num << setw(8) << salary << endl;