Download Visual C++程序设计

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Bra–ket notation wikipedia , lookup

Elementary mathematics wikipedia , lookup

Transcript
48113
软件与通信工程学院 李 刚
[email protected]
13133808285
QQ:4263697
上课时间:周二567节
上课地点:荟庐H113
课程特点:理论实践结合
英汉双语教学
Basic C++ Programming
Lesson 2
1.2 Defining and Initializing a
Data Object
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 sequence from Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13,
and so on
Requirements
• If the user enters 5, we congratulate
her and ask whether she would like
to try another numerical sequence数
列.
• Any other entered value is incorrect,
and we ask the user whether she
would like to guess again.
• To add interest to the program, we
keep a running score based on the
number of correct answers divided
by the number of guesses.
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
Define Variables
Data Type
int
float
double
char
string
…
Var_Name
• any combination of letters,
numbers, and the underscore
• case-sensitive
• cannot begin with a number.
• cannot be a keyword
√
√
√
√
user_name, User_name, uSeR_nAmE, and user_Name
refers to distinct objects
1_name ×
name_1 √
delete ×
class ×
Variables Initialization:
it is a good idea to initialize data objects even
if the value simply indicates that the object
has no useful value as yet
int num_tries = 0, num_right = 0;
An alternative : constructor syntax
int num_tries( 0 ), num_right(0);
constructor syntax
It works well with class objects that require
multiple initial values初值, as in the complex
number class case:
#include <complex>
complex<double> 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.
Constants
常数:
We use const before a variable
definition and initialization to represent
a constant value:
const int max_tries = 3;
const double
pi = 3.14159;
• Initialized at once
• No changing afterwards
1.3 Expressions
Operators:
For built-in data types:
arithmetic
relational
logical
compound assignment
Arithmetic Operators
+
*
/
%
addition
subtraction
multiplication
division
remainder
a+b
a-b
a*b
a/b
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
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' );
Conditional
operator
expr
? execute_if_expr_is_true
: execute_if_expr_is_false;
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
Relational operators
==
!=
<
>
<=
>=
equality
inequality
less than
greater than
less than or equal
greater than or equal
Evalutes to true or false
a == b
a != b
a<b
a>b
a <= b
a >= b
Example:
if ( usr_rsp == 'N' )
usr_more = false;
else if ( usr_rsp == 'n' )
usr_more = false;
Logical Operators
|| OR或, &&AND与, !NOT非
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";
Operator Precedance
logical NOT
arithmetic
arithmetic
relational
relational
logical AND
logical OR
assignment
(!)
( *, /, % )
( +, - )
( <, >, <=, >= )
( ==, != )
( && )
( || )
( =, +=, -=, … )
Example
! ival % 2
! (ival % 2 )
*p++
*(p++)
(*p)++
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
!Cann’t miss { }
num_right++;
got_it = true;
} // ends statement block
if Statements
The if statement also supports an else clause.
if ( usr_guess == next_elem )
{
// user guessed correctly
}
else
{
// user guessed incorrectly
}
if-else Statements
The if-else statement
can be nested
/stringed together
usr_guess !=
next_elem
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
// ...
}
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-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
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
}
1.5 How to Use Arrays and
Vectors
6 different numerical sequences数列:
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
vector
const int seq_size
= 18;
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
};
elem_seq[ 0 ] =1;
elem_seq[ 1 ] =2;
……
// initialize elem_seq with values of elem_vals
vector<int> elem_seq( elem_vals, elem_vals+seq_size );
Template class, header:vector
1.6 Pointers Allow for Flexibility
vector<int> fibonacci, lucas, pell, triangular, square,
pentagonal;
Pointer to a
vector<int> *pv = 0;
pv = &fibonacci;
// ...
pv = &lucas;
vector<int> *seq_addrs[ seq_cnt ] = {
&fibonacci, &lucas, &pell,
&triangular, &square, &pentagonal
};
vector
Pointer
array
#include <cstdlib>
vector<int> *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.
if ( pv &&
If pv NOT NULL
! pv->empty() &&
(( *pv )[1] == 1 ))
Dereference pv
Pointed vec NOT
Empty
First elem. eq 1
1.7 Writing and Reading Files
#include <fstream>
File operation header
// 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,
Open in Append
// the file could not be opened
mode
if ( ! outfile )
//…
else
Write to file
{
outfile << usr_name << ' ' << num_tries << ' ' <<
num_right << endl;
}
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
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.
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.
Exercise 1.7
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<string>
object. Iterate over the vector, displaying it to
cout. That done, sort the words using the sort()
generic algorithm,
#include <algorithm>
sort( container.begin(), container.end() );
Then print the sorted words to an output file.
Exercise 1.8
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.
vector<string> msg[4];
Thanks!