Essential C++ Notes
Part2 Procedural Programming
编写函数
返回类型
函数名
参数列表
函数体
代码:
#include <iostream>
using namespace std;
bool fibon_elem ( int pos, int & elem) {
if ( pos < 0 || pos> 1024 ) {
elem = 0 ;
return false ;
}
elem = 1 ;
int n_2 = 1 , n_1 = 1 ;
for ( int ix = 3 ; ix <= pos; ++ ix) {
elem = n_1 + n_2;
n_2 = n_1, n_1 = elem;
}
return true ;
}
bool print_sequence ( int pos) {
if ( pos <= 0 || pos > 1024 ) {
cerr << "Invalid position: " << pos
<< " -- cannot handle request!\n" ;
return false ;
}
cout << "The fibonacci Sequence for "
<< pos << " positions:\n\t" ;
switch ( pos) {
default :
case 2 :
cout << "1 " ;
case 1 :
cout << "1 " ;
break ;
}
int elem;
int n_2 = 1 , n_1 = 1 ;
for ( int ix = 3 ; ix <= pos; ++ ix) {
elem = n_2 + n_1;
n_2 = n_1, n_1 = elem;
cout << elem << ( ( ! ix % 10 ) ? "\n\t" : " " ) ;
}
cout << endl;
return true ;
}
int main ( ) {
int pos;
cout << "Please enter a position:" ;
cin >> pos;
int elem;
if ( fibon_elem ( pos, elem) )
cout << "element # " << pos
<< " is " << elem << endl;
else
{
cout << "Sorry. Could not calculate element # "
<< pos << endl;
}
print_sequence ( pos) ;
return 0 ;
}
代码分析:
考虑周到:这是一个实现斐波拉契数列的函数,定义了pos,在调用函数时考虑到了pos的取值范围,以及int型数据的最大范围,避免了错误产生 bool类型函数:在这里使用了bool类型函数,函数返回的是true/false,要改变的值则是通过值引用来改变,便于通过返回值来辨别运行情况