我是一個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;
}
}
}