斐波那契数列打印—循环练习7


#include
#include

using namespace std;

int main(void) {
int p; //共几位数列
int a=1; //数列前一位
int b=1; //数列后一位
int column; //斐波那契数

cout << "请输入几位斐波那契数列:";
cin >> p;

if(p <= 0) {
	cout << "输入错误!!!" << endl;
	system("pause");
	return 1;
}

if(p == 1) {
	cout << "1" << endl;
	system("pause");
	return 0;
}

if(p == 2) {
	cout << "1 1" << endl;
	system("pause");
	return 0;
}

cout << " 1 1 ";
for(int i=3; i<=p; ++i) {
	column = a+b;
	a = b;
	b = column;
	cout << column << " ";
}
cout << endl;

system("pause");
return 0;

}

/**
循环练习第7关
输出指定项的斐波那契数列.
1, 1, 2, 3, 5, 8, 13, 21, …
**/
1.
a b
1 + 1 = f //f = 2
a = b //a = 1
b = f //b = 2
f = 2
2 = b

a b
1 + 2 = f // f = 3
a = b // a = 2
b = f // b = 3
f = 3
3 = b

a b
2 + 3 = f // f = 5
a = b // a = 2
b = f // b = 5
f = 5
5 = b

斐波那契数列打印—循环练习7_第1张图片
斐波那契数列打印—循环练习7_第2张图片
斐波那契数列打印—循环练习7_第3张图片
斐波那契数列打印—循环练习7_第4张图片

你可能感兴趣的:(c/c++)