#include <iostream>
using namespace std;
long f(int n)
{
long f , g, v;
f = g = 1;
if (n == 0 || n == 1)
return 1;
else
while ( 0 < n--)
{
v = f + g;
g = f;
f = v;
}
return g;
}
int main()
{
int n;
cin >> n;
while ( !(0 <= n && n <= 80) )
{
printf("重新输入!\n");
cin >> n;
}
cout << f(n) << "\n";
system("pause");
return 0;
}
请教一个问,写了斐波那契数列,想显示第80项,尝试了改为long没有效果,该怎么改进呢?谢谢大家!
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
6条回答 默认 最新
crf_moonlight 2018-12-11 14:58关注char数组, 可以显示到100位
如果感觉效率差可以用动态规划改一下
#include <iostream> #include <algorithm> using namespace std; class Number { private: char storage[100]; int length; public: Number(int n) { for (int i = 0; i < 100; i++) { this->storage[i] = 0; } this->length = 0; int cnt = 0; for (; n > 0; cnt++) { this->storage[cnt] = n % 10; n = (n - this->storage[cnt]) / 10; } this->length = cnt; } int GetLength() { return this->length; } int GetDigit(int index) { return this->storage[index]; } void Print() { for (int i = this->length - 1; i >= 0; i--) { cout << int(this->storage[i]); } cout << endl; } void Add(Number that) { int length = max(this->length, that.GetLength()); for (int i = 0; i < length; i++) { int sum = this->storage[i] + that.GetDigit(i); if (sum < 10) { this->storage[i] = sum; } else { this->storage[i] = sum - 10; this->storage[i + 1]++; } } for (int i = 99; i >= this->length; i--) { if (this->storage[i] != 0) { this->length = i + 1; break; } } } }; void f(int n) { if (n == 0 || n == 1) { cout << 1 << endl; return; } auto a = Number(1); auto b = Number(1); for (int i = 1; i < n; i++) { if (i % 2 == 1) { a.Add(b); } else { b.Add(a); } } if (n % 2 == 0) { a.Print(); } else { b.Print(); } } int main() { for (int i = 0; i < 80; i++) { f(i); } }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决评论 打赏 举报无用 1