if(n ==1)
cout<<"1"<<endl;elseif(n ==2)
cout<<"2"<<endl;else{int a =1, b =2, c;for(int i =3; i <= n; i++){// c就是到i级台阶的走法,b就是i-1级,a就是i-2级
c = a + b;
a = b;
b = c;}
cout<<c<<endl;}
5、然而结果并不如人意,因为n给出的最大值可以到5000,此时的结果已经远远超出long long int 范围,因此我们需要嵌入大整数相加的算法(使用数组来进行加法)
二、整体代码
#include<iostream>#include<string>#include<algorithm>
using namespace std;intmain(){int n, i, j, k;
cin>>n;if(n ==1)
cout<<"1"<<endl;elseif(n ==2)
cout<<"2"<<endl;else{
string a ="1", b ="2", c;for(i =3; i <= n; i++){// 大整数加法
c ="";int len1 = a.length(), len2 = b.length(), temp =0;for(j =0; j < len1; j++){
temp =int(a[j]-'0'+ b[j]-'0')+ temp;
c +=char(temp %10+'0');
temp /=10;}for(j; j < len2; j++){
temp =int(b[j]-'0')+ temp;
c +=char(temp %10+'0');
temp /=10;}if(temp)
c +=char(temp +'0');
a = b, b = c;}// 将字符串逆置reverse(c.begin(), c.end());
cout<<c<<endl;}return0;}