Ngôn ngữ lập trình C++ - Chương 3: Hàm

Thực hiện các tính toán toán học thông thường

Include header file <cmath> (hoặc <math.h>)

Cách gọi hàm

tên_hàm (đối_số); hoặc

tên_hàm(đối_số_1, đối_số_2, );

Ví dụ

 cout << sqrt( 900.0 );

Mọi hàm trong thư viện toán đều trả về giá trị kiểu double

các đối số (argument) cho hàm có thể là

hằng - Constants

sqrt( 4 );

biến - Variables

sqrt( x );

biểu thức - Expressions

sqrt( sqrt( x ) ) ;

sqrt( 3 - 6x );

 

 

ppt85 trang | Chuyên mục: C/C++ | Chia sẻ: dkS00TYs | Lượt xem: 1700 | Lượt tải: 1download
Tóm tắt nội dung Ngôn ngữ lập trình C++ - Chương 3: Hàm, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
ition định nghĩa hàm 	return-value-type function-name( parameter-list ){ declarations and statements} danh sách tham số – Parameter list dấu phảy tách các tham số mỗi tham số cần cho biết kiểu dữ liệu của tham số đó Nếu không có đối số, sử dụng void hoặc để trống giá trị trả về – Return-value-type kiểu của giá trị trả về (sử dụng void nếu không trả về giá trị gì) 3.5 Định nghĩa hàm Từ khóa return trả dữ liệu về, và trả điều khiển lại cho nơi gọi (caller) nếu không trả về, sử dụng return; hàm kết thúc khi chạy đến ngoặc phải ( } ) điều khiển cũng được trả về cho nơi gọi Không thể định nghĩa một hàm bên trong một hàm khác Ví dụ về hàm int square( int y ) { return y * y; } int main() { ... cout chú ý: tương đương với (kiểu cũ, trước ANSI C++) tương đương với (kiểu cũ, trước ANSI C++) 3.8 Sinh số ngẫu nhiênRandom Number Generation Hàm rand (thuộc ) i = rand(); Sinh một số nguyên không âm trong đoạn từ 0 đến RAND_MAX (thường là 32767) Lấy tỷ lệ và dịch (scaling and shifting) phép đồng dư (lấy số dư) – Modulus (remainder) operator: % 10 % 3 bằng 1 x % y nằm giữa 0 và y – 1 Ví dụ i = rand() % 6 + 1; “Rand() % 6” sinh một số trong khoảng từ 0 đến 5 (lấy tỷ lệ ) “+ 1” tạo khoảng từ 1 đến 6 (dịch) Tiếp theo: chương trình thả súc sắc fig03_07.cpp(1 of 2) 1 // Fig. 3.7: fig03_07.cpp 2 // Shifted, scaled integers produced by 1 + rand() % 6. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setw; 11 12 #include // contains function prototype for rand 13 14 int main() 15 { 16 // loop 20 times 17 for ( int counter = 1; counter 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setw; 11 12 #include // contains function prototype for rand 13 14 int main() 15 { 16 int frequency1 = 0; 17 int frequency2 = 0; 18 int frequency3 = 0; 19 int frequency4 = 0; 20 int frequency5 = 0; 21 int frequency6 = 0; 22 int face; // represents one roll of the die 23 fig03_08.cpp(2 of 3) 24 // loop 6000 times and summarize results 25 for ( int roll = 1; roll sử dụng trước rand() để đặt hạt giống fig03_09.cpp(1 of 2) 1 // Fig. 3.9: fig03_09.cpp 2 // Randomizing die-rolling program. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include 10 11 using std::setw; 12 13 // contains prototypes for functions srand and rand 14 #include 15 16 // main function begins program execution 17 int main() 18 { 19 unsigned seed; 20 21 cout > seed; 23 srand( seed ); // seed random number generator 24 fig03_09.cpp(2 of 2)fig03_09.cppoutput (1 of 1) 25 // loop 10 times 26 for ( int counter = 1; counter trả về thời gian hiện tại, tính bằng giây Tổng quát về dịnh và lấy tỷ lệ Number = shiftingValue + rand() % scalingFactor shiftingValue = số đầu tiên của khoảng mong muốn scalingFactor = độ rộng của khoảng mong muốn 3.9 Ví dụ: Trò chơi may rủi và Giới thiệu về kiểu enum Kiểu liệt kê - Enumeration tập hợp các số tự nhiên được đặt tên enum typeName {constant1, constant2…}; Các hằng số là các số nguyên bắt đầu từ 0 (mặc định), tăng dần, mỗi lần thêm 1 đơn vị. Các hằng phải có tên riêng Không thể gán giá trị kiểu nguyên cho biến kiểu liệt kê Phải dùng một giá trị thuộc cùng kiểu liệt kê đã được định nghĩa Ví dụ enum Status {CONTINUE, WON, LOST}; enum Foo {Zero, One, Two}; Status enumVar; enumVar = WON; // cannot do enumVar = 1 or enumVar=One 3.9 Ví dụ: Trò chơi may rủi và Giới thiệu về kiểu enum Các hằng kiểu liệt kê có thể có giá trị đặt trước enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}; bắt đầu tại 1, tăng dần mỗi lần thêm 1 Tiếp theo: giả lập trò chơi gieo súc sắc Gieo 2 con súc sắc, được kết quả là tổng hai giá trị gieo được 7 hoặc 11 tại lần gieo đầu tiên: người chơi thắng 2, 3, hoặc 12 tại lần gieo đầu tiên: người chơi thua 4, 5, 6, 8, 9, 10 giá trị gieo được trở thành "điểm" (point) của người chơi người chơi phải gieo được số điểm của mình trước khi gieo được 7 để thắng cuộc fig03_10.cpp(1 of 5) 1 // Fig. 3.10: fig03_10.cpp 2 // Craps. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 // contains function prototypes for functions srand and rand 9 #include 10 11 #include // contains prototype for function time 12 13 int rollDice( void ); // function prototype 14 15 int main() 16 { 17 // enumeration constants represent game status 18 enum Status { CONTINUE, WON, LOST }; 19 20 int sum; 21 int myPoint; 22 23 Status gameStatus; // can contain CONTINUE, WON or LOST 24 fig03_10.cpp(2 of 5) 25 // randomize random number generator using current time 26 srand( time( 0 ) ); 27 28 sum = rollDice(); // first roll of the dice 29 30 // determine game status and point based on sum of dice 31 switch ( sum ) { 32 33 // win on first roll 34 case 7: 35 case 11: 36 gameStatus = WON; 37 break; 38 39 // lose on first roll 40 case 2: 41 case 3: 42 case 12: 43 gameStatus = LOST; 44 break; 45 fig03_10.cpp(3 of 5) 46 // remember point 47 default: 48 gameStatus = CONTINUE; 49 myPoint = sum; 50 cout 4 5 using std::cout; 6 using std::endl; 7 8 void useLocal( void ); // function prototype 9 void useStaticLocal( void ); // function prototype 10 void useGlobal( void ); // function prototype 11 12 int x = 1; // global variable 13 14 int main() 15 { 16 int x = 5; // local variable to main 17 18 cout 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setw; 11 12 unsigned long factorial( unsigned long ); // function prototype 13 14 int main() 15 { 16 // Loop 10 times. During each iteration, calculate 17 // factorial( i ) and display result. 18 for ( int i = 0; i 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 unsigned long fibonacci( unsigned long ); // function prototype 10 11 int main() 12 { 13 unsigned long result, number; 14 15 // obtain integer from user 16 cout > number; 18 19 // calculate fibonacci value for number input by user 20 result = fibonacci( number ); 21 22 // display result 23 cout 4 5 using std::cout; 6 using std::endl; 7 8 void function1(); // function prototype 9 void function2( void ); // function prototype 10 11 int main() 12 { 13 function1(); // call function1 with no arguments 14 function2(); // call function2 with no arguments 15 16 return 0; // indicates successful termination 17 18 } // end main 19 fig03_18.cpp(2 of 2)fig03_18.cppoutput (1 of 1) 20 // function1 uses an empty parameter list to specify that 21 // the function receives no arguments 22 void function1() 23 { 24 cout 5 6 using std::cout; 7 using std::cin; 8 using std::endl; 9 10 // Definition of inline function cube. Definition of function 11 // appears before function is called, so a function prototype 12 // is not required. First line of function definition acts as 13 // the prototype. 14 inline double cube( const double side ) 15 { 16 return side * side * side; // calculate cube 17 18 } // end function cube 19 fig03_19.cpp(2 of 2) fig03_19.cppoutput (1 of 1) 20 int main() 21 { 22 cout > sideValue; 27 28 // calculate cube of sideValue and display result 29 cout 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int x = 3; 11 12 // y refers to (is an alias for) x 13 int &y = x; 14 15 cout 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int x = 3; 11 int &y; // Error: y must be initialized 12 13 cout 5 6 using std::cout; 7 using std::endl; 8 9 int squareByValue( int ); // function prototype 10 void squareByReference( int & ); // function prototype 11 12 int main() 13 { 14 int x = 2; 15 int z = 4; 16 17 // demonstrate squareByValue 18 cout 4 5 using std::cout; 6 using std::endl; 7 8 // function prototype that specifies default arguments 9 int boxVolume( int length = 1, int width = 1, int height = 1 ); 10 11 int main() 12 { 13 // no arguments--use default values for all dimensions 14 cout 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setprecision; 11 12 // define global constant PI 13 const double PI = 3.14159265358979; 14 15 int main() 16 { 17 // define local constant PI 18 const float PI = static_cast( ::PI ); 19 20 // display values of local and global PI constants 21 cout 4 5 using std::cout; 6 using std::endl; 7 8 // function square for int values 9 int square( int x ) 10 { 11 cout typename hoặc class (đồng nghĩa) đặt trước mỗi tham số kiểu là đại diện cho các kiểu cài sẵn (ví dụ int) hoặc các kiểu dữ liệu người dùng chỉ ra các kiểu dữ liệu cho đối số hàm, giá trị trả về, biến địa phương Hàm được định nghĩa như bình thường, ngoại trừ việc sử dụng các kiểu hình thức 3.21	Khuôn mẫu hàm Ví dụ template // or template T square( T value1 ) { return value1 * value1; } T là một kiểu hình thức, được dùng làm tham số kiểu hàm trên trả về giá trị thuộc cùng kiểu với tham số Tại lời gọi hàm, T được thay bằng kiểu dữ liệu thực Nếu là int, mọi T trở thành int int x; int y = square(x); fig03_27.cpp(1 of 3) 1 // Fig. 3.27: fig03_27.cpp 2 // Using a function template. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 // definition of function template maximum 10 template // or template 11 T maximum( T value1, T value2, T value3 ) 12 { 13 T max = value1; 14 15 if ( value2 > max ) 16 max = value2; 17 18 if ( value3 > max ) 19 max = value3; 20 21 return max; 22 23 } // end function template maximum 24 fig03_27.cpp(2 of 3) 25 int main() 26 { 27 // demonstrate maximum with int values 28 int int1, int2, int3; 29 30 cout > int1 >> int2 >> int3; 32 33 // invoke int version of maximum 34 cout > double1 >> double2 >> double3; 42 43 // invoke double version of maximum 44 cout > char1 >> char2 >> char3; 52 53 // invoke char version of maximum 54 cout << "The maximum character value is: " 55 << maximum( char1, char2, char3 ) 56 << endl; 57 58 return 0; // indicates successful termination 59 60 } // end main Input three integer values: 1 2 3 The maximum integer value is: 3   Input three double values: 3.3 2.2 1.1 The maximum double value is: 3.3   Input three characters: A C B The maximum character value is: C 

File đính kèm:

  • pptNgôn ngữ lập trình C++ - Chương 3 Hàm.ppt
Tài liệu liên quan