Chapter 4 Methods - Sun Yat
Download
Report
Transcript Chapter 4 Methods - Sun Yat
Chapter 4
Math Functions, Characters, and
Strings
§4.1 Mathematical Functions
§4.2 Character Type and Operations
§4.3 The string Type
§4.4 Formatting Console Output
§4.5 Simple File I/O
§4.1 Mathematical Functions
• How to estimate the area enclosed by four cities,
given the GPS locations (latitude and longitude) of
these cities?
Charlotte (35.2270869,-80.8431267)
Atlanta
(33.7489954,-84.3879824)
Savannah (32.0835407,-81.0998342)
Need mathematical functions. <cmath>
Orlando (28.5383355,-81.3792365)
2
Trigonometric (三角) Functions
Function
Description
sin(radians)
Returns the trigonometric sine of an angle in radians.
cos(radians)
Returns the trigonometric cosine of an angle in radians.
tan(radians)
Returns the trigonometric tangent of an angle in radians.
asin(a)
Returns the angle in radians for the inverse of sine.
acos(a)
Returns the angle in radians for the inverse of cosine.
atan(a)
Returns the angle in radians for the inverse of tangent.
3
Exponent (指数) Functions
Function
Description
exp(x)
Returns e raised to power of x (ex).
log(x)
Returns the natural logarithm of x (ln(x) = loge(x)).
log10(x)
Returns the base 10 logarithm of x (log10(x)).
pow(a, b)
Returns a raised to the power of b (ab).
sqrt(x)
Returns the square root of x (
x
) for x >= 0.
4
Other Functions
Function
Description
ceil(x)
x is rounded up to its nearest integer. This integer is returned
as a double value.
floor(x)
x is rounded down to its nearest integer. This integer is returned
as a double value.
Function
Description
max(x, y)
returns the greater one of x and y.
min(x, y)
returns the smaller one of x and y.
abs(x)
returns the absolute value of x.
5
Case Study: Computing Angles of a
Triangle
x2, y2
c
a
B
C
x3, y3
A
b
x1, y1
A = acos((a * a - b * b - c * c) / (-2 * b * c))
B = acos((b * b - a * a - c * c) / (-2 * a * c))
C = acos((c * c - b * b - a * a) / (-2 * a * b))
Input: triangle’s x- and y-coordinates
Output: the triangle’s angles.
ComputeAngles
6
§4.2 Character Type and Operations
• char
– the data type for a single character
char letter = 'A';
char numChar = '4';
• Read characters
cout << "Enter a character: ";
char ch;
cin >> ch;
7
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
\'
Single Quote
39
\"
Double Quote
34
8
Appendix B: ASCII Character Set
9
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.25
10
Numeric Operators on Characters
•
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;
11
Check Point
• 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’;
12
Lowercase to Uppercase
Write a program that prompts the user to enter a
lowercase letter and finds its corresponding
uppercase letter.
ToUppercase
You can also use library functions <cstdlib>
tolower(), toupper()
13
Comparing and Testing Characters
Comparing characters comparing ASCII codes
'a' < 'b' : true (97<98)
'a' < 'A' : false (97>65)
‘1’ < '8' : true (49<56)
To test the characters: a digit? an uppercase letter?
i)
Check ASCII directly
if(ch>='A'&&ch<='Z')
cout<<"an uppercase letter\n";
ii) Use functions <cstdlib>
isdigit(), isletter(), islower,…
14
Character Functions
Function
Description
isdigit(ch)
Returns true if the specified character is a digit.
isalpha(ch)
Returns true if the specified character is a letter.
isalnum(ch)
Returns true if the specified character is a letter or digit.
islower(ch)
Returns true if the specified character is a lowercase letter.
isupper(ch)
Returns true if the specified character is an uppercase letter.
isspace(ch)
Returns true if the specified character is a whitespace character.
tolower(ch)
Returns the lowercase of the specified character.
toupper(ch)
Returns the uppercase of the specified character.
<cctype>
CharacterFunctions
15
Case Study: Random Characters
Listing 4.3. A program that prompts the user to
enter two characters, and display a random
character between x and y.
--How to do it?
-- Random numbers in Chapter 3. (srand(), rand())
-- Random characters?
16
Case Study: Random Characters
rand()%10
Returns a random integer
between 0 and 9.
50+rand()%50
Returns a random integer
between 50 and 99.
a +rand()%b
Returns a random number
between a and a + b,
DisplayRandomCharacter
17
Case Study: Guessing Birthdays
A program can determine the day of month of the
birth date.
--based on answers about whether it is in the
following five number sets:
= 19
+
1 3 5 7
9 11 13 15
17 19 21 23
25 27 29 31
Set1
2
10
18
26
3
11
19
27
6
14
22
30
Set2
7
15
23
31
4 5 6 7
12 13 14 15
20 21 22 23
28 29 30 31
8 9 10 11
12 13 14 15
24 25 26 27
28 29 30 31
Set3
Set4
16
20
24
28
17
21
25
29
18
22
26
30
19
23
27
31
Set5
GuessBirthday
18
Case Study: Hexadecimal Digit to
Decimal Value
Write a program that converts a hexadecimal digit
into a decimal value.
HexDigit2Dec
19
§4.3 The string Type
string s;
string message = “Welcome to C++";
Function
Description
length()
Returns the number of characters in this string.
size()
Same as length();
at(index)
Returns the character at the specified index from this string.
20
String Subscript Operator
1
2
3
4
5
message W e
l
c
o
m e
Indices
0
message.at(0)
6
7
8
9 10 11 12 13
t
o
message.length is 14
C +
+
message.at(13)
Each character is associated with a specified index:
stringName[index]
string s = "ABCD";
s[0] = 'P';
cout << s[0] << endl;
21
Concatenating Strings
string message = " Welcome to C++ “;
message += " and programming is fun";
string s3 = s1 + s2;
s3 += ‘!’;
string s = "ABC"+ "DE";
string s = message + "ABC"+ "DE";
22
Comparing Strings
By comparing characters on by one from left to right.
string s1 = "ABC";
string s2 = "ABE";
cout << (s1 == s2) << endl;
cout << (s1 != s2) << endl;
cout << (s1 > s2) << endl;
cout << (s1 >= s2) << endl;
cout << (s1 < s2) << endl;
cout << (s1 <= s2) << endl;
// Displays 0 (false)
// Displays 1 (true)
// Displays 0 (false)
// Displays 0 (false)
// Displays 1 (true)
// Displays 1 (true)
23
Reading Strings
string city;
cout << "Enter a city: ";
cin >> city;
cout << "You entered " << city << endl;
string city;
cout << "Enter a city: ";
getline(cin, city); // getline(cin, city, ‘\n’);
cout << "You entered " << city << endl;
24
Example
Write a program that prompts the user to enter
two cities and displays them in alphabetical
order.
OrderTwoCities
25
Case Study: Lottery Program Using
Strings
One problem can be solved using many different
approaches.
This a revision of the lottery program in Listing 3.7 using
strings.
Lottery
LotteryUsingStrings
26
§4.4 Formatting Console Output
Manipulator
Description
setprecision(n)
sets the precision of a floating-point number
fixed
displays floating-point numbers in fixed-point notation
showpoint
causes a floating-point number to be displayed with
a decimal point and trailing zeros even if it has
no fractional part
setw(width)
specifies the width of a print field
left
justifies the output to the left
right
justifies the output to the right
27
setprecision(n) Manipulator
double number = 12.34567;
cout << setprecision(3) << number << " "
<< setprecision(4) << number << " "
<< setprecision(5) << number << " "
<< setprecision(6) << number << endl;
displays
12.3□12.35□12.346□12.3457
28
fixed Manipulator
double monthlyPayment = 345.4567;
double totalPayment = 78676.887234;
cout << fixed << setprecision(2)
<< monthlyPayment << endl
<< totalPayment << endl;
345.46
78676.89
29
showpoint Manipulator
cout << setprecision(6);
cout << 1.23 << endl;
cout << showpoint << 1.23 << endl;
cout << showpoint << 123.0 << endl;
1.23
1.23000
123.000
30
setw(width) Manipulator
cout << setw(8) << "C++" << setw(6) << 101 << endl;
cout << setw(8) << "Java" << setw(6) << 101 << endl;
cout << setw(8) << "HTML" << setw(6) << 101 << endl;
!!!Affecting only the following one output!!!
8
6
□□□□□C++□□□101
□□□□Java□□□101
□□□□HTML□□□101
31
left and right Manipulators
cout << right;
cout << setw(8) << 1.23 << endl;
cout << setw(8) << 351.34 << endl;
□□□□1.23
□□351.34
1.23□□□□
351.34□□
cout << left;
cout << setw(8) << 1.23<<endl;
cout << setw(8) << 351.34 << endl;
32
§4.5 Simple File Input and Output
• To read input from the keyboard and write
output to the screen/console?
– “cin” and “cout”
• To read and write data from/to a file?
– ifstream and ofstream
33
Simple File Output
1. Create a variable of the ofstream type:
ofstream output;
2. Open the file to do output:
output.open("numbers.txt");
create + open:
ofstream output("numbers.txt");
3. Write data using the insertion operator (<<):
output << 95 << " " << 56 << " " << 34 << endl;
SimpleFileOutput
34
Simple File Input
1. Create a variable of the ifstream type:
ifstream input;
2. Open the file to do input:
input.open("numbers.txt");
create + open:
ifstream input("numbers.txt");
3. Read data using the extraction operator (>>) :
input >> score1 >> score2 >> score3;
SimpleFileInput
35
A Summary
• Mathematical functions <cmath>
• Character data type
– Character vs. Integer
– Character operations
•
•
•
•
Character functions <cstdlib>
The string type
Formatting output
Simple file Input/Output
36
Homework Questions
• In C++, the data type integer and the data
type character can be used interchangeably.
True or false? Why?
37