Chapter 2 Primitive Data Type and Operations

Download Report

Transcript Chapter 2 Primitive Data Type and Operations

Chapter 2 Elementary Programming
编程入门
§2.1 A Simple Program
§2.2 Identifiers and Variables 标示符与变量
§2.3 Assignment statements 赋值语句
§2.4 Numeric Types and Operations 数值类型与操作
§2.5 Expressions and Operators 表达式与运算符
§2.6 Numeric Type Conversions 数值类型转换
§2.7 Software Development Process 软件开发过程
§2.8 Case study and Common Errors
1
§2.1 A Simple Program
• Problem: to compute the area of a circle with
a given radius value
• Solutions/Algorithm:
1) Get the radius value;
2) Compute the area using the formula:
area = π x radius x radius
3) Display the result;
2
int main(){
//Step 1: read in radius
//Step 2: computer area
//Step 3: display the area
}
A Simple Program
Listing 2.1 Computing the Area of a Circle
#include <iostream>
using namespace std;
int main() {
double radius;
double area;
// Step 1: Read in radius
radius = 20;
// Step 2: Compute area
(Including header files)
(Declaration of the main
function)
(Comments)
(Declaration of variables)
(Body statements)
area = radius * radius * 3.14159;
// Step 3: Display the area
cout << "The area is ";
cout << area << std::endl;
return 0;
3
}
ComputeArea
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;
}
4
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;
}
5
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;
}
6
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;
}
7
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;
}
8
radius
area
20
1256.636
print a message to
the console
Reading from the Keyboard
cin
An object to read input from the standard input
device, i.e. keyboard.
cout << “Enter a radius: ”
cin >> radius;
ComputeWithConsoleImput
9
Reading Multiple Values
cin
cin >> x1;
cin>>x2;
…
cin >> x1>>x2>>…;
ComputeAverage
10
Check Point
• How do to read an integer value and a double
value from the keyboard?
• What is the printout if you enter “2 2.5” for:
double width, height;
cin>>width>>height;
cout<<width*height;
…
11
int width, height;
cin>>width>>height;
cout<<width*height;
…
§2.2 Identifiers and Variables
• 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
12
Check Point
• Which of the following identifiers are valid?
miles, Test, a++, --a, 4#R, $4, #12, apps
main, double, int, x, y, radius
13
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
14
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
15
namespace X {
int i;
double j;
}
int main() {
X::i++;
}
• 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;
scout << area;
// Compute the second area
radius = 2.0;
area = radius * radius * 3.14159;
cout << area;
16
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;
17
Declaring + Initializing(初始化)
int x = 1;
double d = 1.4;
int x(1);
double d(1.4);
18
Declare before Use
• Declare vs. Define
– Declare: define it and allocate memory for it to
store data
• A variable must be declared before it can be
used.
double radius, area; // to declare;
cin >> radius;
// to use
area = 3.14 * radius * radius; // to use
19
Check Point
• Any errors?
#include <iostream>
using namespace std;
int main()
{
int i = k +1;
cout << I <<endl;
int i = 1;
cout << i <<endl;
return 0;
}
20
§2.3 Assignment Statements
(赋值语句)
• To assign some value to a variable
x = 1; // Assign 1 to x;
radius = 1.0;// Assign 1.0 to radius
int y = 1;
double radius = 1.0;
x = y + 1;
x = 2*x + 1; //same variable in both sides
y = x = 1;
21
//to multiple variables
Left vs. Right
• Left value: the memory space
of a variable
– x = 1;
• Right value: the content/value
of a variable
– y = x + 1;
22
Memory address Memory content
.
.
.
.
.
.
2000
01001010
2001
01100001
2002
01110110
2003
01100001
2004
00000011
Equation vs. Assignment
• Equation in mathematics:
– x = 2*x + 1
–x=1, 1=x
• Assignment statements in program
– x = 2*x +1
– x = 1 (“1 = x” is invalid)
23
Check Point
• Any errors?
#include <iostream>
using namespace std;
int main()
{
int i = j = k = 1;
return 0;
}
24
Constants(常量)
• Constant
– A value that cannot be changed
• Two kinds of constants
– Named Constant (命名常量)
– Literal (直接常量、字面常量、常值)
25
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;
26
Note: by convention, constants are
named in upper case.
Named Constants
• Listing 2.4 ComputeAreaWithConstant
const double PI = 3.14159;
// Step 1: Read in radius
double radius;
cout << "Enter a radius: ";
cin >> radius;
// Step 2: Compute area
double area = radius * radius * PI;
// Step 3: Display the area
cout << "The area is ";
cout << area << endl;
27
§2.4 Numeric Types and Operations
• Numeric data types
– Integer number
int, short, long
符号位
• Modifiers (修饰符)
– signed vs. unsigned
– Floating-point number
float, double, long double
28
(10000001)2 或 10000001B
signed:
= -1
unsigned: = 129
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
29
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.
• Precision of floating-point numbers
– Limited number of digits ->limited precision
Float type: 7 digits
1234.567342
Significant digits Random digits
30
The Max and Min Constants
• INT_MIN, INT_MAX, LONG_MIN, LONG_MAX
• FLT_MIN, FLT_MAX, DBL_MIN, DBL_MAX
• Defined in header file <limits>
LimitsDemo
31
The sizeof Function
sizeof: the unary operator used to calculate the
sizes of data types.
For example:
cout << sizeof(int)
<< " " << sizeof(long)
<< " " << sizeof(double);
SizeDemo
32
Numeric Literals
• Constant values appear directly in the program
int i = 1;
double x = 3.45;
cout<<3.14*r<<endl;
• Type of literals
– By default: integer is in int type, floating is in double
– Using “F” “f” “L” “l” to change the type explicitly
cout<<3.14F*r<<endl;
33
octal and hex Literals
• Decimal: default one
• Octal: 0????
• Hexadecimal: 0x????
For example:
cout << 0xFFFF << " " << 010<<endl;
34
Numeric Operations
• Numeric 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
35
Integer Division
+, -, *, /, and %
5/2 yields an integer 2.
5.0/2 yields a double value 2.5
By default: integer is in int type, floating is in double
5%2 yields 1 (the remainder of the division)
36
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
37
Example: Displaying Time
Listing 2.7: to convert number of seconds to
“hours + minutes”
DisplayTime
38
Exponent Operations
• Using the pow(a, b) function to compute ab
– A function defined in <cmath>
39
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;
40
§2.5 Expressions and Operators
• Expression 表达式
– 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
41
Operand
Example: Converting Temperatures
Listing 2.8: to convert a Fahrenheit degree to
Celsius using the formula:
celsius  ( )( fahrenheit 32)
5
9
FahrenheitToCelsius
42
Case Study: Displaying the Current Time
Listing 2.9: 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
Current Time
ShowCurrentTime
43
time(0)
Augmented Assignment Operators
44
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.
45
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
46
Check Point
• 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++)
47
§2.6 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
48
Conversion Rules
• From a “smaller” type to a “larger” type
long double
double
float
unsigned long
long
unsigned int
int
49
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;
50
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
51
Example: Keeping Two Digits
After Decimal Points
Listing 2.10: to displays the sales tax with two digits
after the decimal point.
SalesTax
52
Check Point
• 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;
53
§2.7 Software Development Process
To understand the problem:
what the software must do.
The process to obtain
output from input.
Requirement
Specification
System Analysis
System Design
Implementation
Testing
To analyze the data flow:
What is input/output.
Deployment
Coding, to translate the
design into programs.
54
Maintenance
Example: Compute Loan Payments
• Stage 1. Requirement specification
– Allow the user to enter the annual interest rate,
loan amount, and number of years of payments
– Compute and display the monthly payment and
total payment amount
55
Example: Compute Loan Payments
• Stage 2. System analysis
– The output is monthly payment and total payment
– It can be obtained from
loanAmount monthlyInterestRate
1
1
(1  monthlyInterestRate) numberOfYears12
– The necessary input : monthly interest rate,
number of loan years, and loan amount
56
Example: Compute Loan Payments
• Stage 3. System design
Identify the steps in the program (algorithm)
– Let user enter the input
• Annul rate in integer
– Convert annual rate to monthly rate
– Compute monthly payment using the formula
– Compute the total payment amount
– Display results
57
Example: Compute Loan Payments
• Stage 4. Implementation
– Listing 2.11
ComputeLoan
• Stage 5. Testing
– Design test data covering all cases
58
§2.8 Case Study and Common Errors
• The problem:
– To change a given amount of money into smaller
monetary units. $123.5 -> 123 dollars + 2 quarters
• Floating amount in dollars  list of monetary units
• Major steps
59
– Convert dollars into cents
– Divide cents to find dollars
– Divide remaining cents to find quarters
– ….to find dimes, nickels, pennies.
– Display the results
Counting Monetary Units
Listing 2.12. ComputeChange.cpp
ComputeChange
60
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;
61
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;
62
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;
63
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;
64
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;
65
remainingAmount
updated
Common Errors
• Undeclared/Uninitialized variables
– Case sensitive
• Unused variables
• Integer overflow
• Round-off errors
float a = 1000.43;
float b = 1000.0;
count <<a-b<<endl;
– Floating numbers are stored inaccurately
• Unintended integer division
• Forgetting header files
66
Summary
•
•
•
•
•
•
•
•
67
Structure of simple C++ programs
Variables and constants
Numeric data types
Numeric operations
Assignment statements
Expression and operators
Type conversion
Software development procedure
Homework Questions
• Please describe the concept of variable using
your own words.
68