天天看點

學越千山:C語言程式設計練習題(十一)

作者:LearningYard學苑
學越千山:C語言程式設計練習題(十一)

分享興趣,傳播快樂,增長見聞,留下美好!

親愛的您,這裡是LearningYard新學苑。

今天小編為大家帶來

“學越千山:C語言程式設計練習題(十一)”,

歡迎您的通路。

Share interest, spread happiness, increase knowledge, and leave beautiful.

Dear, this is the LearingYard Academy!

Today, the editor brings the “

Learning to Cross a Thousand Mountains:

C Language Programming Exercise

Quesvtion (11)”.

Welcome to visit!

思維導圖

Mind mapping

學越千山:C語言程式設計練習題(十一)

練習題

Exercise questions

學越千山:C語言程式設計練習題(十一)

#include <stdio.h>

int Fib(int n); //函數聲明

//Function declaration

int count; //全局變量

//Global variable

int main()

{

int n,m,i;

printf("Input n:");

scanf("%d",&n);

for (i = 1; i <= n; i++)

{

count = 0; //計算下一項時初始化count

//Initialize count when calculating the next item

m = Fib(i);

printf("Fib(%d)=%d, count=%d\n",i,m,count);

}

return 0;

}

//函數功能:計算fib數列的第n項

//Function function: Calculate the nth term of the fib sequence

int Fib(int n)

{

count++;

if (n == 0) //基線情況

return 0; //Baseline situation

if(n == 1) //基線情況

return 1; //Baseline situation

else //一般情況

return Fib(n-2)+Fib(n-1);

//General situation

}

注意:

全局變量

(1)即不在任何語句塊内定義的變量,在程式任何地方都可以通路它的值,是以全局變量能使函數之間的資料交流更加友善。

(2)如果我們濫用全局變量,也會讓程式變得混亂,因為全局變量可能在任何一個函數被更改,這樣的的調試和維護困難較大。

遞歸函數

(1)任何遞歸函數都應有至少一個基線情況,以保證一般情況遞歸到基線情況時可以順利停止。

(2)一般來說能用遞歸函數解決的都可以用疊代法解決。遞歸函數相較于疊代程式要更直覺、更清晰、可讀性更好、更接近數學公式的表示,但疊代程式的執行效率更高。

Attention:

Global variable

(1) That is, a variable not defined in any statement block can access its value anywhere in the program, so Global variable can make data exchange between functions more convenient.

(2) If we abuse Global variable, the program will also become confused, because Global variable may be changed in any function, which is difficult to debug and maintain.

General recursive function

(1) Any General recursive function should have at least one baseline condition to ensure that the recursion can be stopped smoothly when it reaches the baseline condition in general.

(2) Generally speaking, anything that can be solved by General recursive function can be solved by Iterative method. Compared with iterative programs, General recursive function are more intuitive, clearer, more readable, and closer to the representation of Formula, but the execution efficiency of iterative programs is higher.

學越千山:C語言程式設計練習題(十一)

今天的分享就到這裡了,

如果您對文章有獨特的想法,

歡迎給我們留言。

讓我們相約明天,

祝您今天過得開心快樂!

That's all for today's sharing.

If you have a unique idea about the article,

please leave us a message,

and let us meet tomorrow.

I wish you a nice day!

參考資料:百度翻譯,C語言程式設計第4版(蘇小紅等)

本文由LearningYard新學苑整理并發出,如有侵權請背景留言溝通

繼續閱讀