用C++实现斐波那契数列

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

原文链接: https://www.cnblogs.com/yonggandefeng/p/6275862.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    用C++实现斐波那契数列

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/247539

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午2:19
下一篇 2023年2月14日 上午2:19

相关推荐