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
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
1
Objectives
To know the structure of simple C++
programs
 To know the concept of identifiers, variables,
constants
 To learn the use of assignment statements
and expressions
 To learn primitive data types

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
2
§1.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)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
area = radius * radius * 3.14159;
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
ComputeArea
Run
3
Trace the Execution
allocate memory
for radius
#include <iostream>
int main() {
double radius;
double area;
radius
no value
// Step 1: Read in radius
radius = 20;
// Step 2: Compute area
area = radius * radius * 3.14159;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
4
Trace the Execution
#include <iostream>
int main() {
double radius;
double area;
// Step 1: Read in radius
radius = 20;
memory
radius
no value
area
no value
allocate memory
for area
// Step 2: Compute area
area = radius * radius * 3.14159;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
5
Trace the Execution
assign 20 to radius
#include <iostream>
int main() {
double radius;
double area;
radius
area
20
no value
// Step 1: Read in radius
radius = 20;
// Step 2: Compute area
area = radius * radius * 3.14159;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
6
Trace the Execution
memory
#include <iostream>
int main() {
double radius;
double area;
// Step 1: Read in radius
radius = 20;
radius
area
20
1256.636
compute area and assign it
to variable area
// Step 2: Compute area
area = radius * radius * 3.14159;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
7
Trace the Execution
memory
#include <iostream>
int main() {
double radius;
double area;
radius
area
// Step 1: Read in radius
radius = 20;
20
1256.636
print a message to
the console
// Step 2: Compute area
area = radius * radius * 3.14159;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
// Step 3: Display the area
std::cout << "The area is ";
std::cout << area << std::endl;
}
8
Reading Input from the Keyboard
std::cin
An object to read input from the standard
input device, i.e. keyboard.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
ComputeArea1
Run
9
§1.2 Variables and Constants

Identifier

A sequence of characters that consists of



And start with a letter or an underscore (digit? No!).
An identifier can be of any length in C++ standard


letters, digits, and underscores (_),
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
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
It cannot be used as a013225445X
user-defined name
Data type names, code construct labels, etc.

See Appendix A for a list of reserved words
10
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


Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
std
Namespace is hierarchical
Global
A
B
11
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
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
namespace X {
int i;
double j;
}
int main() {
X::i++;
}
ComputeArea2
Run
12
Variables

Variable


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;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
// Compute the second area
radius = 2.0;
area = radius * radius * 3.14159;
std::cout << area;
13
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;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
14
Assignment Statements
x = 1;
// Assign 1 to x;
radius = 1.0;
// Assign 1.0 to radius;
a = 'A';
// Assign 'A' to a;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
15
Declaring + Initializing
int x = 1;
double d = 1.4;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
16
Constants

Constant


A value that cannot be changed
Two kinds of constants
Named Constant
 Literal

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
17
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;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
Note: by convention, constants are
named in upper case.
18
Literals

Literal


A constant value that appears directly in a
program
Numerical literals
40, 1.3

Character literals
‘a’, “a”, “this is”
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
19
octal and hex Literals
Decimal: default one
 Octal: 0????
 Hexadecimal: 0x????

For example:
cout << 0xFFFF << " " << 010<<endl;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
20
§1.3 Primitive Data Types

4 primitive data types
Integer number
int, short, long
 Floating-point number
float, double, long double
 Character
 Void


符号位
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
Modifiers

signed vs. unsigned
(10000001)2 或 10000001B
signed:
= -1
unsigned: = 129
21
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
double
Negative range:
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
-1.7976931348623157E+308 to -4.9E-324
013225445X
32-bit unsigned
64-bit IEEE 754
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
22
The sizeof Function
sizeof: the unary operator used to calculate
the sizes of data types.
For example:
cout << sizeof(int)
<< " " << sizeof(long)
<< " " << sizeof(double);
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
23
Floating-point Numbers

Floating-point numbers

Numbers with a decimal point
50.534  5.0534e+1


Various representations



its decimal point is moved (i.e., floated) to a new
position.
IEEE 754 Standard etc.
Float and double in C++
1.45 (double) 1.45f (float) 1.45F(float)
Precision of floating-point numbers
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
Limited number of digits ->limited precision
Float type: 7 digits
1234.567342

Significant Random
digits
digits
24
§1.4 Number Operations

Number operators
Name
Meaning
Example
Result
+
Addition
34 + 1
35
-
Subtraction
34.0 – 0.1
33.9
*
Multiplication
300 * 30
9000
/
%
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
Division
1.0 / 2.0
0.5
Remainder
20 % 3
2
25
Integer Division
+, -, *, /, and %
5/2
yields an integer 2.
5.0/2 yields a double value 2.5
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
5%2 yields 1 (the remainder of the division)
26
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
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days
27
Example: Displaying Time
Listing 2.6: to convert number of seconds
to “hours + minutes”
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
DisplayTime
Run
28
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.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
For example:
short value = -32768-1;
29
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
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
Operator
Operand
30
Example: Converting Temperatures
Listing 2.7: to convert a Fahrenheit degree to
Celsius using the formula:
celsius  ( )( fahrenheit 32)
5
9
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
FahrenheitToCelsius
Run
31
Shorthand Operators
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
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
32
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.
Predecrement
Decrements var by 1 and evaluates to the
new value in var after the decrement.
Postdecrement
Evaluates to the original value in var and
decrements var by 1.
--var
var--
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
33
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;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
Note: these operators makes expressions short but more complex.
Avoid using these operators in multiple times such as this: int k = ++i + i.
34
§1.5 Numeric Type Conversions
Consider the following statements:
short i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
Values need to be converted to
different types
35
Conversion Rules

From a “smaller” type to a “larger” type
long double
double
float
unsigned long
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
long
unsigned int
int
36
Type Casting
The technique realizing type conversation
 Implicit casting

double d = 3;

Explicit casting

static_cast
static_cast<T>(v); //or
(T)v;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
--converts the value of the expression v to that of type T
int i = static_cast<int>(3.0);
37
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
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X

Using static_cast to avoid such a warning
38
Example: Keeping Two Digits
After Decimal Points
Listing 2.8: to displays the sales tax with two
digits after the decimal point.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
SalesTax
Run
39
§1.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 Liang,
ch;Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
cin >> ch;
40
Appendix B: ASCII Character Set
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
41
Escape Sequences for Special Characters
Character Escape Sequence
Name
ASCII Code
\b
Backspace
8
\t
Tab
9
\n
Linefeed
10
\f
Formfeed
12
\r
Carriage Return
13
\\
Backslash
92
\'
\"
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
Single Quote
39
Double Quote
34
42
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
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
char c =0xFF41;//c is assigned to be (41)16
c=65
43
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/uppercse letters are
consecutive integers starting from the code for
'a'/'A'.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
static_cast<char>('A' + (ch - 'a'))
char ch = 'a'; cout << ++ch;
44
§1.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)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
ComputeLoan
Run
45
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
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
ComputeChange
Run
46
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;
remainingAmount
1156
remainingAmount
initialized
// 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;
Liang,of
Introduction
C++the
Programming,
(c) 2007
Pearson Education, Inc. All rights reserved.
// Find the number
nickelsto in
remaining
amount
013225445X
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
47
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;
1156
11
numberOfOneDollars
assigned
// Find the number of dimes in the remaining amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
Liang,of
Introduction
C++the
Programming,
(c) 2007
Pearson Education, Inc. All rights reserved.
// Find the number
nickelsto in
remaining
amount
013225445X
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
48
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;
remainingAmount
updated
// Find the number of dimes in the remaining amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
Liang,of
Introduction
C++the
Programming,
(c) 2007
Pearson Education, Inc. All rights reserved.
// Find the number
nickelsto in
remaining
amount
013225445X
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
49
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;
numberOfOneQuarters
assigned
Liang,of
Introduction
C++the
Programming,
(c) 2007
Pearson Education, Inc. All rights reserved.
// Find the number
nickelsto in
remaining
amount
013225445X
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
50
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;
remainingAmount
updated
Liang,of
Introduction
C++the
Programming,
(c) 2007
Pearson Education, Inc. All rights reserved.
// Find the number
nickelsto in
remaining
amount
013225445X
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
// Find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
51
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
Current Time
Unix Epoch
Liang, Introduction
to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
01-01-1970
00:00:00 GMT
ShowCurrentTime
time(0)
Run
52
Summary
Structure of simple C++ programs
 Variables and constants
 Primitive data types and operations


Numeric data and character
Expressions
 Type casting

Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.
013225445X
53