Chapter 2 Primitive Data Type and Operations

Download Report

Transcript Chapter 2 Primitive Data Type and Operations

Chapter 2 Primitive Data Types
and Operations
基本数据类型与运算
§2.1 Simple Programs
§2.2 Variables and Constants 变量与常量
§2.3 Primitive Data Types 基本数据类型
§2.4 Number Operations 数值运算
§2.5 Numeric Type Conversions 数值类型转换
§2.6 Character Data Type 字符类型
§2.7 Case Studies 实例
1
§2.1 Simple Programs
Listing 2.1 Computing the Area of a Circle
#include <iostream>
int main() {
double radius;
double area;
// Step 1: Read in radius
(Including header files)
(Declaration of the main
function)
(Declaration of variables)
radius = 20;
(Comments)
// Step 2: Compute area
(Body statements)
area = radius * radius * 3.14159;
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
2
ComputeArea
Run
Trace the Execution
allocate memory
for radius
#include <iostream>
int main() {
double radius;
double area;
// Step 1: Read in radius
radius = 20;
// Step 2: Compute area
area = radius * radius * 3.14159;
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
3
radius
no value
Trace the Execution
#include <iostream>
int main() {
double radius;
double area;
// Step 1: Read in radius
radius = 20;
// Step 2: Compute area
area = radius * radius * 3.14159;
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
4
memory
radius
no value
area
no value
allocate memory
for area
Trace the Execution
assign 20 to radius
#include <iostream>
int main() {
double radius;
double area;
// Step 1: Read in radius
radius = 20;
// Step 2: Compute area
area = radius * radius * 3.14159;
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
5
radius
area
20
no value
Trace the Execution
memory
#include <iostream>
int main() {
double radius;
double area;
// Step 1: Read in radius
radius = 20;
// Step 2: Compute area
area = radius * radius * 3.14159;
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
6
radius
area
20
1256.636
compute area and assign it
to variable area
Trace the Execution
memory
#include <iostream>
int main() {
double radius;
double area;
// Step 1: Read in radius
radius = 20;
// Step 2: Compute area
area = radius * radius * 3.14159;
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
7
radius
area
20
1256.636
print a message to
the console
Reading Input from the Keyboard
std::cin
An object to read input from the standard input
device, i.e. keyboard.
double radius;
std::cout << "Enter a radius: ";
std::cin >> radius;
ComputeArea1
8
Run
§2.2 Variables and Constants
• Identifier (标识符)
– A sequence of characters that consists of
• letters, digits, and underscores (_),
– And start with a letter or an underscore (digit? No!),
– Case sensitive.
• An identifier can be of any length in C++ standard
– but your C++ compiler may impose some restriction. Use
identifiers of 31 characters or fewer to ensure portability.
• Reserved word (保留字、关键字)
– A special word that predefined in the language’s formal
specifications
– It cannot be used as a user-defined name
– Data type names, code construct labels, etc.
• See Appendix A for a list of reserved words
9
Namespace (命名空间)
• What is std? The “standard” namespace
– std::cout, std::endl, and std::cin
• Namespace
– A container of a group of identifiers
– To resolve potential naming conflicts
• Two special namespaces
– The global namespace: the default one
– std: the namespace of C++ standard
• Namespace is hierarchical
10
std
Global
A
B
Namespace
• How to use namespace
– Add prefix to every reference:
std::cout<<“Hello”;
– Add an overall statement:
using namespace std; //use the whole space
using std::cout;
//use the specific identifier
• How to declare namespace
11
namespace X {
int i;
double j;
}
int main() {
X::i++;
}
ComputeArea2
Run
• Variable
Variables (变量)
– an identifier standing for a value that may vary
• Three elements
– name,
– type, and
– value
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
std::cout << area;
// Compute the second area
radius = 2.0;
area = radius * radius * 3.14159;
std::cout << area;
12
Declaring(声明) Variables
int x;
// Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a;
// Declare a to be a
// character variable;
datatype variableName;
Declare before use!
13
Assignment Statements (赋值语句)
14
x = 1;
// Assign 1 to x;
radius = 1.0;
// Assign 1.0 to radius;
a = 'A';
// Assign 'A' to a;
Declaring + Initializing(初始化)
int x = 1;
double d = 1.4;
15
Constants(常量)
• Constant
– A value that cannot be changed
• Two kinds of constants
– Named Constant (命名常量)
– Literal (直接常量、字面常量、常值)
16
Named Constant
• Named constant
– An identifier that stands for a constant, i.e.
• The value of a named constant cannot be reassigned
const datatype CONSTANTNAME = VALUE;
const double PI = 3.14159;
const int SIZE = 3;
17
Note: by convention, constants are
named in upper case.
Literals
• Literal
– A constant value that appears directly in a
program
• Numerical literals
40, 1.3
• Character literals
‘a’, “a”, “this is”
18
octal and hex Literals
• Decimal: default one
• Octal: 0????
• Hexadecimal: 0x????
For example:
cout << 0xFFFF << " " << 010<<endl;
19
Review Questions
• Which of the following identifiers are valid?
x, X, a++, --a, 4#R, $4, _apps, r3
20
§2.3 Primitive Data Types
• 4 primitive data types
– Integer number
int, short, long
符号位
• Modifiers (修饰符)
– signed vs. unsigned
– Floating-point number
float, double, long double
– Character
– Void
21
(10000001)2 或 10000001B
signed:
= -1
unsigned: = 129
Floating-point Numbers
• Floating-point numbers
– Numbers with a decimal point
50.534  5.0534e+1
– its decimal point is moved (i.e., floated) to a new position.
• Various representations
– IEEE 754 Standard etc.
• Float and double in C++
1.45 (double) 1.45f (float) 1.45F(float)
• Precision of floating-point numbers
– Limited number of digits ->limited precision
Float type: 7 digits
1234.567342
Significant digits Random digits
22
Numerical Data Types
Name
Synonymy
Range
Storage Size
short
short int
–215 (-32,768) to 215–1 (32,767)
16-bit signed
unsigned short
unsigned short int
0 to 216–1 (65535)
16-bit unsigned
–231 (-2147483648) to 231–1 (2147483647) 32-bit signed
int
unsigned int
signed
long
unsigned
0 to 232–1 (4294967295)
long int
unsigned long
float
unsigned long int
–231 (-2147483648) to 231–1 (2147483647) 32-bit signed
0 to 232–1 (4294967295)
32-bit unsigned
Negative range:
32-bit IEEE 754
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
32-bit unsigned
double
Negative range:
64-bit IEEE 754
-1.7976931348623157E+308 to -4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308
long double
Negative range:
-1.18E+4932 to 3.37E-4932
Positive range:
3.37E-4932 to 1.18E+4932
Significant decimal digits: 19
80-bit
The length may be different for different compilers and computers
23
The sizeof Function
sizeof: the unary operator used to calculate the
sizes of data types.
For example:
cout << sizeof(int)
<< " " << sizeof(long)
<< " " << sizeof(double);
24
Review Questions
• What’s the result of following expressions?
sizeof(9000)
sizeof(2L)
sizeof(2.3)
sizeof(5.4f)
25
§2.4 Number Operations
• Number operators (运算符)
Name
Meaning
Example
Result
+
Addition
34 + 1
35
-
Subtraction
34.0 – 0.1
33.9
*
Multiplication
300 * 30
9000
/
Division
1.0 / 2.0
0.5
%
Remainder
20 % 3
2
26
Integer Division
+, -, *, /, and %
5/2 yields an integer 2.
5.0/2 yields a double value 2.5
5%2 yields 1 (the remainder of the division)
27
Remainder Operator
• Remainder is very useful
– To determine whether a number is even or odd,
– To determine some enumerable values,
–…
Saturday is the 6th day in a week
A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days
28
Example: Displaying Time
Listing 2.6: to convert number of seconds to
“hours + minutes”
DisplayTime
29
Run
Overflow and Underflow
• Overflow(向上溢出), the condition that
– a variable is assigned a value that is greater than
the maximum value in the value range.
For example:
short abc;
abc = 32767 + 1;
• Underflow(向下溢出), the condition that
– a variable is assigned a value that is smaller than
the minimum value in the value range.
For example:
short value = -32768-1;
30
Arithmetic Expressions (算术表达式)
Straightforward translation from
mathematical expression
 The same operator precedence

3  4 x 10( y  5)(a  b  c)
4 9 x

 9( 
)
5
x
x
y
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
Operator
31
Operand
Example: Converting Temperatures
Listing 2.7: to convert a Fahrenheit degree to
Celsius using the formula:
celsius  ( )( fahrenheit 32)
5
9
FahrenheitToCelsius
32
Run
Shorthand Operators
33
Operator Example
Equivalent
+=
i += 8
i = i + 8
-=
f -= 8.0
f = f - 8.0
*=
i *= 8
i = i * 8
/=
i /= 8
i = i / 8
%=
i %= 8
i = i % 8
Increment/Decrement Operators
Operator
Name
Description
++var
Preincrement
Increments var by 1 and evaluates to the
new value in var after the increment.
var++
Postincrement
Evaluates to the original value in var and
increments var by 1.
--var
Predecrement
Decrements var by 1 and evaluates to the
new value in var after the decrement.
var--
Postdecrement
Evaluates to the original value in var and
decrements var by 1.
34
Example: Increment and Decrement
int i = 10;
int newNum = 10 * i++;
i++
int i = 10;
int newNum = 10 * (++i);
++i
Same effect as
int newNum = 10 * i;
i = i + 1;
Same effect as
i = i + 1;
int newNum = 10 * i;
Note: these operators makes expressions short but more complex.
Avoid using these operators in multiple times such as this: int k = ++i + i
35
Review Questions
• Write down the value of “a” and “d” with
int a=1 and double d = 1.0.
a=46/9
a=46%9+4*4-2
a=45+(43%5)*((23*3)%2)
d=4+d*d+4
d+=1.5*3+(a++)
36
§2.5 Numeric Type Conversions
Consider the following statements(语句):
short i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Values need to be converted to
different types
37
Conversion Rules
• From a “smaller” type to a “larger” type
long double
double
float
unsigned long
long
unsigned int
int
38
Type Casting (类型转换)
• The technique realizing type conversation
• Implicit casting
double d = 3;
• Explicit casting
– static_cast
static_cast<T>(v); //or
(T)v;
--converts the value of the expression v to that of type T
int i = static_cast<int>(3.0);
int i = (int)3.0;
39
Notes for Casting
1. Casting does not change the variable being cast.
double d = 4.5;
int i = static_cast<int>(d); // d is not changed
2. The GNU C++ compiler will give a warning when
you narrow a type
– Using static_cast to avoid such a warning
40
Example: Keeping Two Digits
After Decimal Points
Listing 2.8: to displays the sales tax with two digits
after the decimal point.
SalesTax
41
Run
Review Questions
• Show the following output and count how
many type conversions are done.
double f = 12.5F;
f = static_cast<int>(f);
int i = f;
cout<<“f is “<< f <<endl;
cout<<“i is “<< i <<endl;
42
§2.6 Character Data Type
• char
– the data type for a single character
char letter = 'A';
char numChar = '4';
• Read characters
cout << "Enter a character: ";
char ch;
cin >> ch;
43
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
44
Escape Sequences for Special Characters
45
Character Escape Sequence
Name
ASCII Code
\b
Backspace
8
\t
Tab
9
\n
Linefeed
10
\f
Formfeed
12
\r
Carriage Return
13
\\
Backslash
92
\'
Single Quote
39
\"
Double Quote
34
Casting between Char and Numbers
• The char type is treated as if it is an integer of the
byte size
int i = 'a'; // <==> int i = (int)'a';
char c = 97; // <==> char c = (char)97;
• char type ~numeric types
char c =0xFF41; //c is assigned to be (41)16
c=65
46
Notes
•
All numeric operators can be applied to char
operands.
int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51
cout << "i is " << i << endl; // i is decimal 101
i is 101
int j = 2 + 'a'; // (int)'a' is 97
j is 99
cout << "j is " << j << endl;
99 is the ASCII code for c
cout << j << " is the ASCII code for " << (char)j << endl;
•
The ASCII for lowercase/uppercase letters are
consecutive integers starting from the code for
'a'/'A'.
static_cast<char>('A' + (ch - 'a'))
char ch = 'a'; cout << ++ch;
47
Review Questions
• Which of the following are correct character
literals?
‘l’, ‘\t’, ‘&’, ‘\b’, ‘\n’
• Evaluate the following variables
int a = ‘a’;
int b = ‘b’ + 2;
int c = b + ‘3’;
48
§2.7 Case studies
Listing 2.9: to compute the monthly payment
and total payment
loanAm ount m onthlyInterestRate
1
1
numberOfYe ars 12
(1  m onthlyInterestRate)
ComputeLoan
49
Run
Example: Counting Monetary Units
Listing 2.10: to convert amount in decimal
representing dollars and cents to a report listing
the monetary equivalent in single dollars,
quarters, dimes, nickels, and pennies.
$123.5 -> 123 dollars + 2 quarters
ComputeChange
50
Run
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
// Find the number of dimes in the remaining amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
// Find the number of nickels in the remaining amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
51
remainingAmount
1156
remainingAmount
initialized
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
remainingAmount
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
numberOfOneDollars
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
// Find the number of dimes in the remaining amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
// Find the number of nickels in the remaining amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
52
1156
11
numberOfOneDollars
assigned
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
remainingAmount
56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
numberOfOneDollars
11
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
// Find the number of dimes in the remaining amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
// Find the number of nickels in the remaining amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
53
remainingAmount
updated
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
remainingAmount
56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
numberOfOneDollars
11
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
numberOfOneQuarters
2
// Find the number of dimes in the remaining amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
// Find the number of nickels in the remaining amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
54
numberOfOneQuarters
assigned
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100);
remainingAmount
6
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
numberOfOneDollars
11
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
numberOfQuarters
2
// Find the number of dimes in the remaining amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
// Find the number of nickels in the remaining amount
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
55
remainingAmount
updated
Example: Displaying Current Time
Listing 2.11: To display the current time in GMT in the
format hour:minute:second such as 1:45:19.
Hints: the time(0) function in the ctime header file returns
the current time in seconds elapsed since the time 00:00:00
on January 1, 1970 GMT.
Elapsed
time
Time
Unix Epoch
01-01-1970
00:00:00 GMT
ShowCurrentTime
56
Current Time
time(0)
Run
Summary
• Structure of simple C++ programs
• Variables and constants
• Primitive data types and operations
– Numeric data and character
• Expressions
• Type casting
57
Homework Questions
• In C++, the data type integer and the data
type character can be used interchangeably.
True or false? Why?
58