天天看點

C語言_兔子問題(斐波那契數列)

2020年9月2日 10:35:31

// 古典問題:有一對兔子,從出生後第3個月起每個月都生一對兔子

// 小兔子長到第三個月後每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數為多少?

第一道代碼:

// 古典問題:有一對兔子,從出生後第3個月起每個月都生一對兔子
// 小兔子長到第三個月後每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數為多少?

#include <stdio.h>
#include <stdlib.h>


int main(void)
{
	long f1, f2;
	int i;
	f1 = f2 = 1;

	for (i = 1; i <= 20; i++)  // 輸出前 40 個數,每次輸出 2 個; 執行 20 次循環
	{
		printf("%12ld %12ld", f1, f2);  // 長整型, 12個字元,右對齊; 中間有空格

		if (i % 2 == 0)  // 一次輸出 2 個, 兩次輸出 4 個。這條語句的目的是:一行輸出 4 個
			printf("\n");

		f1 = f1 + f2;
		f2 = f1 + f2;
	}
	system("pause");

	return;
}

           

運作結果:

C語言_兔子問題(斐波那契數列)

第二道代碼:

#include <stdio.h>

int main(void)
{
	int a[24] = { 1,1 };  //定義一個數組,數組含有 24 個元素,其中第一、二個元素分别是 1,1
	int m;
	for (m = 0; m < 24; m++)
	{
		if (m >= 2)
			a[m] = a[m - 1] + a[m - 2];

		printf("第 %d 個月有 %d 對兔子\n", m + 1, a[m]);
	}
	return;
}

           

運作結果:

C語言_兔子問題(斐波那契數列)

-------------分界線-------------

補充:将上面兩道代碼合成一道代碼,用指針子函數調用。

時間:2020年9月4日 07:55:30

#include <stdio.h>
#include <stdlib.h>

void Method2(int *, int len);

int main(void)
{
	long f1, f2;
	int i;
	f1 = f2 = 1;

	for (i = 1; i <= 20; i++)  
	{
		printf("%12ld %12ld", f1, f2);  

		if (i % 2 == 0) 
			printf("\n");

		f1 = f1 + f2;
		f2 = f1 + f2;
	}
	system("pause");
	printf("\n");
	
	int a[24] = { 1,1 };   // 子涵數需要用到的數組寫在 main函數裡 
	Method2(a, 24);
	
	system("pause");
	return;
}

void Method2(int * p, int len)
{
	int m;
	for (m = 0; m < len; ++m)  // m < len, 而不能直接寫成 m < 24 
	{
		if (m >= 2)
			p[m] = p[m - 1] + p[m - 2];  // 這裡寫 p[m] 而不能寫成 a[m] 

		printf("第 %d 個月有 %d 對兔子\n", m + 1, p[m]);
	}
	return;
}

           

運作結果:

C語言_兔子問題(斐波那契數列)

繼續閱讀