Essential C++ (2.1)

Essential C++ Notes

Part2 Procedural Programming

编写函数

  1. 返回类型

  2. 函数名

  3. 参数列表

  4. 函数体

    代码:

   #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;
   }
   

代码分析:

  1. 考虑周到:这是一个实现斐波拉契数列的函数,定义了pos,在调用函数时考虑到了pos的取值范围,以及int型数据的最大范围,避免了错误产生
  2. bool类型函数:在这里使用了bool类型函数,函数返回的是true/false,要改变的值则是通过值引用来改变,便于通过返回值来辨别运行情况
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值