essential c++ 第二章第一节的代码

#include< iostream >

using namespace std;

bool fibo( int pos, int & elem );
bool fibo_display( int pos );

int main()
{
  int pos;
  int elem=0;
  bool bl = true;
  char ch;


  while( bl )
  {
 cout<<" input the pos : ";
 cin>>pos;

 if(fibo( pos, elem ))
 cout<<" the num at the pos "<<pos<<" is "<<elem<<endl;

 fibo_display( pos );

 cout<<" Do you want to continue,Y/N ? ";
 cin>>ch;
 if( ch == 'N' || ch == 'n' )
  bl = false;
  }

  return 0;

}

bool fibo( int pos, int & elem )
{
 if( pos <= 0 || pos > 1024 )
 {
  elem = 0;
  return false;
 }

 elem = 1;
 int n_1 = 1;
 int n_2 = 1;

 for( int ix = 2; ix < pos; ix++ )
 {
  elem = n_1 + n_2;
  n_1 = n_2;
  n_2 = elem;
 }

 return true;
}


//  由于这里并没有什么意义,只是用来显示这个数列,所以也可以用一个void返回类型的,
//  但里面的return语句是要改写的。
bool fibo_display( int pos )
{
 int elem;

 if( pos <= 0 || pos > 1024 )
 {
  elem = 1;
  return false;
 }

 // 此处很值得欣赏的。。。。
 switch( pos )
 {
 
 // break;
 case 2:
  cout<< " elem : 1 ";
  //break;
 default:
  cout<< " elem : 1 ";
 case 1:
  cout<< "  1 ";
  break;
 }

 int n_1 = 1;
 int n_2 = 1;

 for( int ix = 2; ix < pos; ix++ )
 {
  elem = n_1 + n_2;
  n_1 = n_2;
  n_2 = elem;
  cout<< elem << " ";

 //要想在此处控制每行都是十行的元素这样写好像是不行的。还要改写的。

  if(!(ix%10))
   cout<<endl;
 }
 cout<<endl;

 return true;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值