C 語言中不同型別的函式是什麼?
函式大致分為兩種型別,如下所示:
- 預定義函式
- 使用者自定義函式
預定義(或)庫函式
這些函式已在系統庫中定義。
程式設計師可以重用系統庫中現有的程式碼,這有助於編寫無錯誤的程式碼。
使用者必須瞭解函式的語法。
例如,sqrt() 函式在 math.h 庫中可用,其用法為 y= sqrt (x),其中 x= 數字必須為正數。
如果 x 值為 25,即 y = sqrt (25),則 'y' = 5。
同樣,printf() 在 stdio.h 庫中可用,clrscr() 在 conio.h 庫中可用。
程式
#include<stdio.h> #include<conio.h> #include<math.h> main (){ int x,y; clrscr (); printf (“enter a positive number”); scanf (“ %d”, &x) y = sqrt(x); printf(“squareroot = %d”, y); getch(); }
輸出
Enter a positive number 25 Squareroot = 5
使用者自定義函式
這些函式必須由程式設計師或使用者定義。
程式設計師必須為這些函式編寫程式碼,並在使用前對其進行適當的測試。
函式的語法由使用者給出,因此無需包含任何標頭檔案。
例如,main()、swap()、sum() 等是一些使用者自定義函式。
示例
#include<stdio.h> #include<conio.h> main (){ int sum (int, int); int a, b, c; printf (“enter 2 numbers”); scanf (“ %d %d”, &a ,&b) c = sum (a,b); printf(“sum = %d”, c); getch(); } int sum (int a, int b){ int c; c=a+b; return c; }
輸出
Enter 2 numbers 10 20 Sum = 30
廣告