Академический Документы
Профессиональный Документы
Культура Документы
Operations
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 1
Objectives
To write C++ programs to perform simple calculations
(§2.2).
To read input from the keyboard using the cin object
(§2.3).
To simplify programming by omitting the std:: prefix
(§2.4).
To use identifiers to name variables, constants, functions,
and classes (§2.5).
To use variables to store data (§§2.6-2.7).
To program with assignment statements and assignment
expressions (§2.7).
To use constants to store permanent data (§2.8).
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 2
Objectives (cont.)
To declare variables using numeric data types (§2.9).
To use operators to write numeric expressions (§2.9).
To convert numbers to a different type using casting
(§2.10).
To represent character using the char type (§2.11).
To become familiar with C++ documentation,
programming style, and naming conventions (§2.13).
To distinguish syntax errors, runtime errors, and logic
errors (§2.14).
To debug logic errors (§2.15).
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 3
Example Program
Listing 2.1: Computing the Area of a
Circle
This program computes the area of the
circle.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 4
animation
int main() {
radius no value
double radius;
double area;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 5
animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 6
animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 7
animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 8
animation
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 9
Reading Input from the
#include <iostream> Keyboard
] int main() {
double radius;
double area;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 10
Omitting the std:: Prefix
You have noticed that std::cout, std::endl, and
std::cin all start with std::.
std means the standard namespace. C++ divides the
world into “namespaces” to resolve potential
naming conflicts.
std::cout means that cout belongs to the standard
namespace.
To avoid typing “std::”:
– add the statement: using namespace std;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 11
#include <iostream>
Omitting the std::
using namespace std;
Prefix (cont.)
int main() {
double radius;
double area;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 13
Variables
// 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. 0
13225445X 15
Assignment Statements
x = 1; // Assign 1 to x;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 16
Declaring and Initializing
in One Step
int x = 1;
double d = 1.4;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 17
Named Constants
const datatype CONSTANTNAME = VALUE;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 18
Numerical Data Types
Name Synonymy Range Storage Size
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 19
sizeof Function
You can use the sizeof function to find the size of a type.
For example, the following statement displays the size of
int, long, and double on your machine.
cout << sizeof(int) << " " << sizeof(long) << " " <<
sizeof(double);
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 20
Synonymous Types
short int is same as short.
unsigned short int is same as unsigned short.
unsigned int is same as unsigned.
long int is same as long.
unsigned long int is same as unsigned long.
E.g.,
short int i = 2;
is same as
short i = 2;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 21
Numeric Literals
int i = 34;
long k = 1000000;
double d = 5.0;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 22
What Are floating-point?
The float and double types are used to represent
numbers with a decimal point.
Why are they called floating-point numbers?
These numbers are stored in scientific notation.
When a number such as 50.534e+1 is converted
into scientific notation such as 5.0534, its
decimal point is moved (i.e., floated) to a new
position.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 23
Numeric Operators
+ Addition 34 + 1 35
% Remainder 20 % 3 2
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 24
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. 0
13225445X 25
Remainder Operator
3%2=1
8%2=0
33 % 2 = 1
DisplayTime Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 27
Overflow
When a variable is assigned a value that is
too large to be stored, it causes overflow. For
example, executing the following statement
causes overflow, because the largest value
that can be stored in a variable of the short
type is 32767. 32768 is too large.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 29
Arithmetic Expressions
3 4 x 10( y 5)(a b c) 4 9 x
9( )
5 x x y
is translated to
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 30
Your Turn: Converting Temperatures
Write a program that converts a Fahrenheit degree
to Celsius using the formula:
celsius ( 95 )( fahrenheit 32)
FahrenheitToCelsius Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 31
Shorthand Assignment 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. 0
13225445X 32
Increment and
Decrement Operators
Operator Name Description
++var preincrement The expression increments by 1 and
evaluates to the new value in var after
the increment.
var++ postincrement The expression (var++) evaluates to the
original value in var and increments var
by 1.
--var predecrement The expression (--var) decrements var by
1 and evaluates to the new value in var
after the decrement.
var-- postdecrement The expression (var--) evaluates to the
original value in var and decrements var
by 1.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 33
Increment and
Decrement Operators, cont.
int i = 10; Same effect as
int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 34
Increment and
Decrement Operators, cont.
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. 0
13225445X 36
Conversion Rules
When performing a binary operation involving two operands of different
types, Java automatically converts the operand based on the following rules:
Explicit casting
int i = static_cast<int>(3.0);
(type narrowing)
int i = (int)3.9;
(Fraction part is truncated)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 38
NOTE
Casting does not change the variable being cast.
For example, d is not changed after casting in the
following code:
double d = 4.5;
int i = static_cast<int>(d); // d is not changed
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 39
Example: Keeping Two Digits After
Decimal Points
Write a program that displays the sales tax with two
digits after the decimal point.
SalesTax Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 40
Character Data Type
char letter = 'A'; //(ASCII)
char numChar = '4'; //(ASCII)
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 42
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. 0
13225445X 43
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. 0
13225445X 44
ASCII Character Set, cont.
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. 0
13225445X 45
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 46
Numeric Operators on Characters
The char type is treated as if it is an integer of the byte size. All numeric operators
can be applied to char operands. A char operand is automatically cast into a
number if the other operand is a number or a character. For example, the following
statements
Display
i is 101
j is 99
99 is the ASCII code for character c
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 47
Note
The ASCII number for lowercase letters are consecutive
integers starting from the code for 'a', then for 'b', 'c', ...,
and 'z'.
The same is true for the uppercase letters. Furthermore, the
ASCII code for 'a' is greater than the code for 'A'. So 'a' -
'A' is the same as 'b' - 'B'.
For a lowercase letter ch, its corresponding uppercase letter
is
static_cast<char>('A' + (ch - 'a')).
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 48
Example:
Computing Loan Payments
This program lets the user enter the interest
rate, number of years, and loan amount and
computes monthly payment and total
payment.
loanAmount monthlyInterestRate
1 1
numberOfYe ars12
(1 monthlyInterestRate )
Compute Loan Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 49
Example: Monetary Units
ComputeChange Run
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 50
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 1156
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; remainingAmount
remainingAmount = remainingAmount % 100;
initialized
// Find the number of quarters in the remaining amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 51
animation
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 1156
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 52
animation
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 53
animation
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 56
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 54
animation
Trace ComputeChange
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 6
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; numberOfOneDollars 11
remainingAmount = remainingAmount % 100;
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 55
Example: Displaying Current Time
Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
/* ctime example */
#include <iostream>
#include <time.h>
using namespace std;
int main ()
{
time_t rawtime;
time ( &rawtime );
cout << "The current local time is:"<< ctime (&rawtime);
return 0;
}
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 56
Programming Style and
Documentation
• Appropriate Comments
• Naming Conventions
• Proper Indentation and Spacing Lines
• Block Styles
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. 0
13225445X 57