假设我们有从[0]到[14]的15个数字满足:
a[0]=4
a[i]=pow(sqrt(a[i-1])*2-1, 2) for i>=1 and i<=14
Run Code Online (Sandbox Code Playgroud)
我需要打印出从[0]到[14]的所有值,每个数字在一行上,所以我写下面的代码(C++,Code :: Blocks):
#include <iostream>
#include <cmath>
using namespace std;
#define maxN 15
int i[maxN]; int n=15;
int main()
{
i[0]=2;
cout<<4<<endl;
for (int k=1; k<n; k++){
i[k]=i[k-1]*2-1;
cout<<pow(i[k],2)<<"\t"<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果是:
4
9
25
81
289
1089
4225
16641
66049
263169
1.05062e+006
4.1984e+006
1.67854e+007
6.71252e+007
2.68468e+008
Run Code Online (Sandbox Code Playgroud)
最后五个数字不正确(因为整数溢出).
在上面的"for"循环中,我改变了这一行
cout<<pow(i[k],2)<<"\t"<<endl;
Run Code Online (Sandbox Code Playgroud)
至
cout<<(long) pow(i[k],2)<<"\t"<<endl;
Run Code Online (Sandbox Code Playgroud)
这一次,结果是:
4
9
24
81
289
1089
4224
16641
66048
263168
1050625
4198400
16785408
67125248
268468224 …Run Code Online (Sandbox Code Playgroud)