我是一个C++初学者,控制台输出斐波那契数列。
代码如下:
//"斐波那契数列"V1.0
//李国良于2017年1月12日编写完成
#include <iostream>
#include <Windows.h>
using namespace std;
const int num = 10000;
const int ArSize = 1000;
void functionOne(int num);
void functionTwo(int num);
int main()
{
SetConsoleTitle("斐波纳契数列");
cout << "long long类型的最大值为:" << LLONG_MAX << endl;
cout << "unsigned long long类型的最大值为:" << ULLONG_MAX << endl;
cout << "long类型的最大值为:" << LONG_MAX << endl;
cout << "unsigned long类型的最大值为:" << ULONG_MAX << endl;
cout << "int类型的最大值为:" << INT_MAX << endl;
cout << "unsigned int类型的最大值为:" << UINT_MAX << endl;
functionTwo(num);
system("pause");
return 0;
}
void functionOne(int num)
{
cout << "本程序会依次输出斐波纳契数列,超过93数据就会溢出。" << endl;
unsigned long long a = 1;
unsigned long long b = 1;
unsigned long long c;
for (int i = 1; i <= num; ++i)
{
if (i <= 2)
{
cout << i << " " << 1 << endl;
}
else
{
c = a + b;
cout << i << " " << c << endl;
a = b;
b = c;
}
}
}
void functionTwo(int num)
{
cout << "本程序会依次输出斐波纳契数列,数字长度超过数组上限就会自动停止输出。" << endl;
int a[ArSize];
int b[ArSize];
int c[ArSize];
static int x = 0;
static bool y = false;
for (int i = 0; i < ArSize; ++i)
{
a[i] = b[i] = c[i] = 0;
}
a[0] = b[0] = 1;
for (int i = 1; i <= num; ++i)
{
if (i <= 2)
{
cout << 1 << endl;
}
else
{
for (int j = 0; j < ArSize; ++j)
{
if (x == 0)
{
if (a[j] + b[j] == 0)
{
c[j] = 0;
}
else
{
c[j] = (a[j] + b[j]) % 10;
x = (a[j] + b[j]) / 10;
}
if (j == ArSize - 1 && x == 1)
{
cout << "数字长度已超过数组上限,自动停止..." << endl;
return;
}
continue;
}
if (x == 1)
{
c[j] = (a[j] + b[j] + x) % 10;
x = (a[j] + b[j] + x) / 10;
if (j == ArSize - 1 && x == 1)
{
cout << "数字长度已超过数组上限,自动停止..." << endl;
return;
}
}
}
x = 0;
cout << i << " ";
for (int j = ArSize - 1; j >= 0; --j)
{
if (c[j] != 0)
{
y = true;
}
if (y)
{
cout << c[j];
a[j] = b[j];
b[j] = c[j];
}
}
y = false;
cout << endl;
}
}
}