Download presentation
Presentation is loading. Please wait.
Published byToby Curtis Modified over 8 years ago
1
软件与通信工程学院 李 刚 teacherlg@163.com 13133808285 QQ:4263697 上课时间:周二 567 节 上课地点:荟庐 H113 课程特点:理论实践结合 英汉双语教学 48113
2
Basic C++ Programming Lesson 2
3
1.2 Defining and Initializing a Data Object quiz quiz We display two numbers representing a numerical sequence and then request our user to identify the next value in the sequence. The values 2,3 form two consecutive elements of a numerical sequence. What is the next value? The values 2,3 form two consecutive elements of a numerical sequence. What is the next value? The sequence from Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, and so on
4
If the user enters 5, we congratulate her and ask whether she would like to try another numerical sequence 数 列. To add interest to the program, we keep a running score based on the number of correct answers divided by the number of guesses. Any other entered value is incorrect, and we ask the user whether she would like to guess again. Requirements
5
Variables needed: the string class object to hold the name of the user; three integer objects to hold, in turn, 1) the user's guess, 2) the number of guesses, and 3) the number of correct guesses; and a floating point object to hold the user's score
6
Define Variables Data TypeVar_Name int float double char string … any combination of letters, numbers, and the underscore case-sensitive cannot begin with a number. cannot be a keyword
7
user_name, User_name, uSeR_nAmE, and user_Name refers to distinct objects 1_name × name_1 √ delete × class × √ √ √ √
8
Variables Initialization: num_triesnum_right int num_tries = 0, num_right = 0; num_tries int num_tries( 0 ), num_right(0); it is a good idea to initialize data objects even if the value simply indicates that the object has no useful value as yet An alternative : constructor syntax
9
It works well with class objects that require multiple initial values 初值, as in the complex number class case: constructor syntax #include complex purei( 0, 7 ); template class The template class mechanism allows programmer s to defer deciding on the data type to use for a template class. It allows the programmer to insert a placeholder that is later bound to an actual data type.
10
We use const before a variable definition and initialization to represent a constant value: Constants 常数 : const int max_tries = 3; const double pi = 3.14159; Initialized at once No changing afterwards
11
1.3 Expressions Operators: For built-in data types: arithmetic relational logical compound assignment
12
Arithmetic Operators + addition a + b - subtraction a - b * multiplication a * b / division a / b % remainder a % b 5 / 3 evaluates to 1 while 5 % 3 evaluates to 2 5 / 4 evaluates to 1 while 5 % 4 evaluates to 1 5 / 5 evaluates to 1 while 5 % 5 evaluates to 0
13
Remainder operator const int line_size = 8; int cnt = 1; // these statements are executed many times, with // a_string representing a different value each time // and cnt growing by one with each execution... cout << a_string << ( cnt % line_size ? ' ' : '\n' ); expr ? execute_if_expr_is_true : execute_if_expr_is_false; Conditional operator
14
Compound assignment operator cnt += 2; // add 2 to the current value of cnt: cnt = cnt + 2; increment and decrement operators cnt++; // add 1 to the current value of cnt cnt--; // subtract 1 from the current value of cnt int tries = 0; cout << "Are you ready for try #" << ++tries << "?\n"; Prefix version int tries = 1; cout << "Are you ready for try #" << tries++ << "?\n"; Postfix version
15
Relational operators == equality a == b != inequalitya != b < less than a < b > greater than a > b <= less than or equal a <= b >= greater than or equal a >= b Evalutes to true or false
16
Example : if ( usr_rsp == 'N' ) usr_more = false; else if ( usr_rsp == 'n' ) usr_more = false;
17
Logical Operators if ( usr_rsp == 'n' || usr_rsp == 'n' ) // logical OR usr_more = false; //----------------------------------------------------------------- if ( password && // logical AND validate( password ) && ( acct = retrieve_acct_info(password) )) // process account... //----------------------------------------------------------------- if ( usr_more == false ) //if ( ! usr_more ) // logical NOT cout << "Your score for this session is " << usr_score << " Bye!\n"; if ( usr_rsp == 'n' || usr_rsp == 'n' ) // logical OR usr_more = false; //----------------------------------------------------------------- if ( password && // logical AND validate( password ) && ( acct = retrieve_acct_info(password) )) // process account... //----------------------------------------------------------------- if ( usr_more == false ) //if ( ! usr_more ) // logical NOT cout << "Your score for this session is " << usr_score << " Bye!\n"; || OR 或, &&AND 与, !NOT 非
18
Operator Precedance logical NOT ( ! ) arithmetic ( *, /, % ) arithmetic ( +, - ) relational (, = ) relational ( ==, != ) logical AND ( && ) logical OR ( || ) assignment ( =, +=, -=, … ) logical NOT ( ! ) arithmetic ( *, /, % ) arithmetic ( +, - ) relational (, = ) relational ( ==, != ) logical AND ( && ) logical OR ( || ) assignment ( =, +=, -=, … )
19
Example ! ival % 2 *p++ *(p++) ! (ival % 2 ) (*p)++
20
1.4 Writing Conditional and Loop Statements // single if if ( usr_rsp == 'N' || usr_rsp == 'n' ) go_for_it = false; //compound statements if ( usr_guess == next_elem ) { // begins statement block num_right++; got_it = true; } // ends statement block !Cann’t miss { }
21
if Statements The if statement also supports an else clause. if ( usr_guess == next_elem ) { // user guessed correctly } else { // user guessed incorrectly } if ( usr_guess == next_elem ) { // user guessed correctly } else { // user guessed incorrectly }
22
if-else Statements The if-else statement can be nested /stringed together if ( usr_guess == next_elem ) { // user guessed correctly } else { // user guessed incorrectly if ( num_tries == 1 ) //... else if ( num_tries == 2 ) //... else if ( num_tries == 3 ) //... else //... } if ( usr_guess == next_elem ) { // user guessed correctly } else { // user guessed incorrectly if ( num_tries == 1 ) //... else if ( num_tries == 2 ) //... else if ( num_tries == 3 ) //... else //... } usr_guess != next_elem
23
Switch-case statements switch ( num_tries ) //replace the if’s before this page { case 1: cout << "Oops! Nice guess but not quite it.\n"; break; case 2: cout << "Hmm. Sorry. Wrong again.\n"; break; default: cout << "It must be getting pretty frustrating by now!\n"; break; } switch ( num_tries ) //replace the if’s before this page { case 1: cout << "Oops! Nice guess but not quite it.\n"; break; case 2: cout << "Hmm. Sorry. Wrong again.\n"; break; default: cout << "It must be getting pretty frustrating by now!\n"; break; }
24
Switch-case statements switch ( next_char ) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': ++vowel_cnt; break; //... } Fall through Fall through
25
Loop Statements The while loop: while the user wants to guess a sequence { display the sequence while the guess is not correct and the user wants to guess again }
26
1.5 How to Use Arrays and Vectors Fibonacci: 1, 1, 2, 3, 5, 8, 13, 21 Lucas: 1, 3, 4, 7, 11, 18, 29, 47 Pell: 1, 2, 5, 12, 29, 70, 169, 408 Triangular: 1, 3, 6, 10, 15, 21, 28, 36 Square: 1, 4, 9, 16, 25, 36, 49, 64 Pentagonal: 1, 5, 12, 22, 35, 51, 70, 92 Fibonacci: 1, 1, 2, 3, 5, 8, 13, 21 Lucas: 1, 3, 4, 7, 11, 18, 29, 47 Pell: 1, 2, 5, 12, 29, 70, 169, 408 Triangular: 1, 3, 6, 10, 15, 21, 28, 36 Square: 1, 4, 9, 16, 25, 36, 49, 64 Pentagonal: 1, 5, 12, 22, 35, 51, 70, 92 6 different numerical sequences 数列 :
27
vector int elem_seq[ seq_size ] = { 1, 2, 3, // Fibonacci 3, 4, 7, // Lucas 2, 5, 12, // Pell 3, 6, 10, //Triangular 4, 9, 16, // Square 5, 12, 22 // Pentagonal }; // initialize elem_seq with values of elem_vals vector elem_seq( elem_vals, elem_vals+seq_size ); const int seq_size = 18; Template class , header:vector elem_seq[ 0 ] =1; elem_seq[ 1 ] =2; ……
28
1.6 Pointers Allow for Flexibility vector fibonacci, lucas, pell, triangular, square, pentagonal; vector *pv = 0; pv = &fibonacci; //... pv = &lucas; vector *seq_addrs[ seq_cnt ] = { &fibonacci, &lucas, &pell, &triangular, &square, &pentagonal }; Pointer to a vector Pointer array
29
#include vector *current_vec = 0; const int seq_cnt=6; srand( seq_cnt ); //... for ( int ix = 0; ix < seq_cnt; ++ix ) { seq_index = rand() % seq_cnt; current_vec = seq_addrs[ seq_index ]; // all element display is implemented // indirectly through current_vec } #include vector *current_vec = 0; const int seq_cnt=6; srand( seq_cnt ); //... for ( int ix = 0; ix < seq_cnt; ++ix ) { seq_index = rand() % seq_cnt; current_vec = seq_addrs[ seq_index ]; // all element display is implemented // indirectly through current_vec } Replace stdlib.c Random number seed Random number gen.
30
if ( pv && ! pv->empty() && (( *pv )[1] == 1 )) If pv NOT NULL Pointed vec NOT Empty First elem. eq 1 Dereference pv
31
1.7 Writing and Reading Files #include // seq_data.txt is opened in append mode // new data is added at the end of the file ofstream outfile( "seq_data.txt", ios_base::app ); //if outfile evaluates as false, // the file could not be opened if ( ! outfile ) //… else { outfile << usr_name << ' ' << num_tries << ' ' << num_right << endl; } File operation header Open in Append mode Write to file
32
Read data from a file // infile opened in output mode ifstream infile( "seq_data.txt" ); if ( ! infile ) { // open failed for some reason... } while ( infile >> name ) { infile >> nt >> nc; //... } Open for read Open successful? Read in from file, word by word
33
Exercise 1.5 Write a program to ask the user his or her name. Read the response. Confirm that the input is at least two characters in length. If the name seems valid, respond to the user. Provide two implementations: one using a C-style character string, and the other using a string class object.
34
Exercise 1.6 Write a program to read in a sequence of integers from standard input. Place the values, in turn, in a built-in array and a vector. Iterate over the containers to sum the values. Display the sum and average of the entered values to standard output.
35
Using your favorite editor, type two or more lines of text into a file. Write a program to open the file, reading each word into a vector object. Iterate over the vector, displaying it to cout. That done, sort the words using the sort() generic algorithm, #include sort( container.begin(), container.end() ); Then print the sorted words to an output file. Exercise 1.7
36
The switch statement of Section 1.4 displays a different consolation message based on the number of wrong guesses. Replace this with an array of four string messages that can be indexed based on the number of wrong guesses. Exercise 1.8 vector msg[4];
37
Thanks!
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.