SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Downloaden Sie, um offline zu lesen
函式
 何謂函式
 內建函式
 自定函式
 函式的參數與引數
 遞迴函式
 變數的有效範圍與生命期
Revised on June 28, 2021
Make
each
day
count
 設計程式時,常會發現⼀些具有特定功能⽽⼜重複出現的程式片段,
將這樣的程式片段獨立出來,必要時給予⼀些參數就能呼叫執⾏使⽤,
如此⼀來,這個程式片段就可以成為⼀個可重複使⽤的程式單元,在
C 語言我們稱之為函式 (Function)
 C 語言的函式分為兩類
 系統內建函式 (Library Functions)
 使⽤者自定函式 (User Defined Functions)
 內建函式如同是⼀個「⿊盒⼦」(black box),我們不需要了解函式內
部的的程式設計細節,也無法做更改,只要知道給予怎樣的參數可以
得到什麼結果
何謂函式 1/2
2
黑盒子
函
式
介
面
呼叫函式(引數)
內建函式 個人程式
Make
each
day
count
void sort(int[] data) {
...
}
...
sort(data1);
...
sort(data2);
...
 自定函式是使⽤者自己依需求整理程式碼所建立,可以隨發展需求調
整更改。良好的規劃與設計自定函式有以下好處
 函式可以重複使⽤,提高生產力
 將系統分割成多個程式單元,可以交付多人共同設計,不僅縮短程式開發
時間,也可以達到程式模組化的目的
 有助於提高程式可讀性,也讓程式的除錯及維護更加容易
何謂函式 2/2
3
返回
自定函式
主程式
Make
each
day
count
 C 語言的編譯器提供⼀個已定義好的函式庫集合稱為標準函式庫
 在標準函式庫裡有:輸出入函式、數學運算函式、字元函式、字串函
式、轉換函式、檔案輸出入函式、時間函式、亂數函式等
 每個內建函式的函式原型宣告都放在標頭檔 (header file)
內建函式 1/2
4
標頭檔 函式群
stdio.h
printf, scanf, gets, puts, getchar, putchar, fclose, feof, fgets, fputs,
fread, fopen, fwrite, rewind, abs
stdlib.h atof, atoi, atol, log, itoa, pow, rand, random, randomize, srand
string.h strcmp, strcpy, strcat, strlen, strtok
ctype.h isalnum, isalpha, isdigit, ispunct, isspace
math.h acos, asin, atan, atof, poly, ceil, cos, div, exp, floor, sin, sqrt, tan
time.h time, gettime, getdate, settime, setdate
io.h eof, open, close, filelength, write, read
conio.h getche, getch, clrscr
Make
each
day
count
 要使⽤內建函式,必須在程式開頭處使⽤ #include 前置指令含入內建函
式的標頭檔
#include <stdio.h>
#include <math.h>
#define PI 3.14159
void std_func(){
double r;
int x;
printf("n x:角度值 t r:弳度值 t sin tt csc");
printf("n========================================================");
for(x = 30; x <= 150; x += 30){
r = PI * (x / 180.0);
printf("n %3d tt %.5f t %.5f t %.5f", x, r, sin(r), 1 / sin(r));
}
}
內建函式 2/2
5
Make
each
day
count
 人體PSI生理週期
 體力 (physical) 週期
 對應協調、體力、健康,出生日算起每23天為⼀週期
 情緒 (sensitive) 波動週期
 對應創造力、敏感性、心情、領悟力、洞察力,從出生日算起每28天為
⼀週期
 智力 (intellectual) 強弱週期
 對應警覺性、分析力、邏輯性、記憶力、溝通能力,從出生日算起每33
天為⼀週期
 PSI生理週期曲線始於基線位置 (0%),表示個體出生時的狀態
Lab 計算PSI 生理週期 1/4
6
Make
each
day
count
#include <math.h>
#include <time.h>
#define PCYCLE 23
#define SCYCLE 28
#define ICYCLE 33
#define PI 3.14159
void psi_cycle(){
int days, pdays, sdays, idays;
float punit, sunit, iunit;
int year_start, month_start, day_start;
int year_end, month_end, day_end;
int y2, m2, d2;
int y1, m1, d1;
time_t nowtime;
struct tm *timeinfo;
printf("請輸入出生年月日(例1995-10-06):");
scanf("%d-%d-%d", &year_start, &month_start, &day_start);
printf("生日是%d-%d-%dn", year_start, month_start, day_start);
Lab 計算PSI 生理週期 2/4
7
Make
each
day
count
//獲取操作當天的日期
time (&nowtime );
timeinfo = localtime (&nowtime );
month_end = 1 + timeinfo->tm_mon; //月份值是0-11, 所以要加1
year_end = 1900 + timeinfo->tm_year; //年份起始值是1900,所以要加1900
day_end = timeinfo->tm_mday; //當月的日期值
printf("今天是%d-%d-%dn", year_end, month_end, day_end);
//計算相隔天數。都換算為到0年3月1日的天數,再相減
m1 = (month_start + 9) % 12;
y1 = year_start - m1/10;
d1 = 365 * y1 + y1 / 4 - y1 / 100 + y1 / 400 + (m1 * 306 + 5) / 10 +
(day_start - 1);
m2 = (month_end + 9) % 12;
y2 = year_end - m2 / 10;
d2 = 365 * y2 + y2 / 4 - y2 / 100 + y2 / 400 + (m2 * 306 + 5) / 10 +
(day_end - 1);
days = d2 - d1;
printf("相隔%d天n", days);
Lab 計算PSI 生理週期 3/4
8
Make
each
day
count
//計算PSI週期天數
pdays = days % PCYCLE;
sdays = days % PCYCLE;
idays = days % PCYCLE;
//計算PSI週期值並顯示
punit = 2 * PI / PCYCLE;
sunit = 2 * PI / SCYCLE;
iunit = 2 * PI / ICYCLE;
printf("體力時鐘週期處於%3.0f%%n", sin(pdays * punit) * 100);
printf("情緒時鐘週期處於%3.0f%%n", sin(sdays * sunit) * 100);
printf("智力時鐘週期處於%3.0f%%n", sin(idays * iunit) * 100);
}
Lab 計算PSI 生理週期 4/4
9
Make
each
day
count
 自訂函式包括二個部份:函式原型宣告及函式定義
 函式原型 (function prototype) 宣告
 函式原型就是函式介面,目的在告知編譯器,程式中該如何使⽤該函式。
如果函式定義是在函式呼叫指令之後,必須在函式呼叫指令之前宣告函式
原型,否則會出現編譯錯誤
 函式原型宣告語法如下:
傳回值資料型別 函式名稱(引數1資料型別, 引數2資料型別, …);
double myfunc(int, int);
 如果函式沒有回傳值,則在函式名稱前面加上 void;如果函式沒有引數,
則在函式名稱後面括弧內填入 void
void myfunc(void);
 雖然新版編譯器允許不宣告函式原型,對於良好撰寫風格的C程式碼來說,
函式⼀定要在使⽤前宣告
自訂函式 1/3
10
Make
each
day
count
 函式定義 (function definition) 就是函式的程式區塊,語法如下:
 例如:
_Bool isPrime(int n) {
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) break;
}
return (i > sqrt(n));
}
自訂函式 2/3
11
函式傳回值之資料型別,
若函式沒有傳回值則將ret_type指定為 void
自訂函式名稱
傳給函式的引數,其格式如同變數宣告;
如果沒有引數,則函式名稱後接空括號
指令敘述,
就是函式的實作 (implements)
有傳回值時,必須使用 return 敘述回傳資料
Make
each
day
count
 呼叫函式
 完成函式定義後,就可以將該函式當成⼀個新的指令敘述使⽤
_Bool isPrime(int); //函式原型宣告
int main(int argc, char* argv[]){
int num;
printf("輸入整數值:");
scanf("%d", &num);
if (isPrime(num))
printf("%d是質數", num);
else
printf("%d不是質數", num);
}
_Bool isPrime(int n){
for (i = 2; i <= sqrt(n); i++){
if (n % i == 0) break;
}
return (i > sqrt(n));
}
自訂函式 3/3
12
呼叫函式
返回主程式
Make
each
day
count
 傳值呼叫 (call by value )
 主程式把資料值複製⼀份給函式之引數保存 (另⼀個記憶體位置的值),因
此函式中不管如何存取引數資料,都不會影響到主程式的資料值
函式引數的傳遞方式 1/6
13
10
20
10
20
&num1
&a
&num2
&b
call_by_value(num1, num2);
主程式變數 函式引數
void call_by_value(int a,int b){
...
}
Make
each
day
count
void swap_by_value(int a, int b){
int temp;
printf("a = %d, b = %dn", a, b);
temp = a;
a = b;
b = temp;
printf("a = %d, b = %dn", a, b);
}
void main(){
int num1 = 10, num2 = 20;
printf("num1 = %d, num2 = %dn", num1, num2);
swap_by_value(num1, num2);
printf("num1 = %d, num2 = %dn", num1, num2);
}
函式引數的傳遞方式 2/6
14
Make
each
day
count
 傳址呼叫 (call by address)
 主程式把儲存資料的記憶體位置傳到函式之引數,因此引數與主程式是共
⽤同⼀個記憶體位置之資料,
void call_by_address(int* a, int* b){
...
}
函式引數的傳遞方式 3/6
15
10
20
&num1
&num2
&num1
&a
&num2
&b
call_by_address(&num1, &num2);
主程式變數 函式引數
*a
*b
&取址運算子:&num表示變數num的記憶體位址
*指標運算子:*a表示到變數a所指示的記憶體位址讀取資料
1
2
1
2
Make
each
day
count
void swap_by_address(int* a, int* b){
int temp;
printf("*a = %d, *b = %dn", *a, *b);
temp = *a;
*a = *b;
*b = temp;
printf("*a = %d, *b = %dn", *a, *b);
}
void main(){
int num1 = 10, num2 = 20;
printf("num1 = %d, num2 = %dn", num1, num2);
swap_by_address(&num1, &num2);
printf("num1 = %d, num2 = %dn", num1, num2);
}
函式引數的傳遞方式 4/6
16
Make
each
day
count
 陣列資料傳遞
 函式之間引數使⽤個別陣列元素,就與⼀般變數傳遞的情況⼀樣,為傳值
呼叫
void myFun(int, int);
int main(int argc, char* argv[]) {
int var1 = 10;
int myArr[5] = {2, 5, 6, 4, 7};
myFun(var1, myArr[3]);
}
void myFun(int a, int b) {
}
函式引數的傳遞方式 5/6
17
傳值 傳值
Make
each
day
count
 函式之間引數使⽤整個陣列,則為傳址呼叫
void myFun(int, int[]);
int main(int argc, char* argv[]) {
int var1 = 10;
int myArr[5] = {2, 5, 6, 4, 7};
myFun(var1, myArr);
}
void myFun(int a, int arr[]) {
}
函式引數的傳遞方式 6/6
18
傳值 傳址
Make
each
day
count
int bubble_sort(int data[], int n){
int i, j, flag, temp;
for (i = 0; i < n - 1; i++){ //n個數字排序,只⽤n-1回合
flag = 0; //每回合清除交換旗號
for (j = 0; j < n – i - 1; j++) {
if (data[j] > data[j + 1]) {
temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
flag = 1; //表示發生過交換
}
}
if (flag == 0) break; //此回合沒有發生交換,表示資料己排序
}
}
Lab 設計泡泡排序函式 1/2
19
Make
each
day
count
 測試泡泡排序
void main(){
int n, i;
int *data;
printf("Number of data: ");
scanf("%d", &n);
data = (int *)malloc(n * sizeof(int));
printf("Numbers to be sorted: ");
for(i = 0; i < n; i++)
scanf("%d", &data[i]);
printf("n");
bubble_sort(data, n);
printf("Numbers Sorted: ");
for(i = 0; i < n; i++)
printf("%d ", data[i]);
free(data);
}
Lab 設計泡泡排序函式 2/2
20
Make
each
day
count
#include <stdio.h>
void find_bound(int n, int data[], int *min, int *max){
//設計函式,從data[]找出最大值及最小值
}
void main(){
int i, n, max, min, *data;
printf("輸入資料個數:");
scanf("%d", &n);
data = (int *)malloc(n * sizeof(int));
printf("輸入%d筆整數值(數值間以空白鍵區隔):", n);
for (i = 0; i < n; i++) scanf("%d", &data[i]);
find_bound(...); //呼叫find_bound()函式,...必須改為參數群
printf("最大值為%d%,最小值為%d", max, min);
free(data);
}
實作練習 設計尋找極值函式 1/2
21
Make
each
day
count
 遞迴函式, 簡單地說就是⼀個呼叫自己的函式
 計算 1 加到 N
 疊代 (iterative) 方式
int sum(int n){
int i, sum = 0;
for (i = 1; i <= n; i++)
sum = sum + i;
return sum;
}
遞迴函式 (Recursive) 1/6
23
Make
each
day
count
 遞迴 (recursive) 方式
int sum(int n){
if (n == 1)
return 1;
else
return sum(n - 1) + n;
}
 要完成 sum(n) 的呼叫必須先完成 sum(n-1) 的呼叫,再把結果加上n,即
為 sum(n) 的結果;
 ⽽要完成 sum(n-1),必須再呼叫 sum(n-2),先算出這個結果,再加上 n-1
就是 sum(n) 的結果了; 如此⼀直下去,直到呼叫 sum(1) 時函式很清楚地
知道結果為 1,於是立刻可以完成 sum(2)的呼叫,即 sum(1)+2 為 3;接下
去完成 sum(3) 的呼叫,得到 sum(2)+3 為 6,… 最後完成 sum(n) 的呼叫
遞迴函式 (Recursive) 2/6
24
Make
each
day
count
遞迴函式 (Recursive) 3/6
25
sum(10)
sum(9) + 10
sum(8) + 9
sum(7) + 8
sum(6) + 7
sum(5) + 6
sum(4) + 5
sum(3) + 4
sum(2) + 3
sum(1) + 2
=1
45
55
3
6
10
15
21
28
36
Make
each
day
count
 什麼樣的問題適合⽤遞迴函式來解決?
 ⼀個問題如果可以拆解成規模較小但是性質和原問題完全⼀樣的問題的時
候, 就可以考慮⽤遞迴函式來處理
 連加、連乘 (階乘)
 輾轉相除
 搜尋
 排序
 老鼠走迷宮
 遞迴程式的結束
 設計遞迴程式時,主體雖然是第 n 步驟和第 n-1 步驟之間的關係,但是⼀
個非常容易忘掉的部份則是結束條件的測試
遞迴函式 (Recursive) 4/6
26
Make
each
day
count
 費氏級數 (Fibonacci):𝑓 𝑛
𝑓 𝑛 1 𝑓 𝑛 2 ,𝑛 2
1
0
,𝑛 1
,𝑛 0
 疊代 (iterative) 方式
int fib(int n){
int i, a1 = 0, a2 = 1, a3;
if (n == 1) return 1;
if (n == 0) return 0;
for (i = 1; i < n; i++){
a3 = a1 + a2;
a1 = a2;
a2 = a3;
}
return a3;
}
遞迴函式 (Recursive) 5/6
27
Make
each
day
count
 遞迴 (recursive) 方式
int fibr(int n){
if (n == 1) return 1;
if (n == 0) return 0;
return fibr(n - 1) + fibr(n - 2);
}
遞迴函式 (Recursive) 6/6
28
fibr(5)
fibr(4) fibr(3)
fibr(3)
fibr(1)
fibr(1)
fibr(2)
fibr(0)
fibr(1)
fibr(2)
fibr(0)
fibr(1)
fibr(2)
fibr(0)
fibr(1)
1 0
0 0
1 1 1
1
2
2
1
1
1
3
Make
each
day
count
 Quick Sort是⼀種「把大問題分成小問題處理 (Divide and Conquer)」
的方法,概念如下:
 在數列中任意挑選⼀個數,稱為 pivot,然後調整數列,使得所有在 pivot
左邊的數,都比 pivot 還小,⽽在 pivot 右邊的數都比 pivot 大
 接著,將所有在 pivot 左邊的數視為「新的數列」,所有在 pivot 右邊的
數視為「另⼀個新的數列」,「分別」重複上述步驟 (選 pivot、調整數
列),直到分不出「新的數列」為止
 時間複雜度:平圴 O(NlogN)
Lab 快速排序 (Quick Sort) 1/5
29
Make
each
day
count
Lab 快速排序 (Quick Sort) 2/6
30
首先以 54 做為 pivot
Make
each
day
count
 資料交換函式
void swap(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
 快速排序函式
void quick_sort(int data[], int left, int right){
int pivot, leftmark, rightmark;
if (left >= right) return;
pivot = data[left];
leftmark = left + 1;
rightmark = right;
Lab 快速排序 (Quick Sort) 3/5
31
left right
pivot
leftmark rightmark
Make
each
day
count
while (1){
while (leftmark <= right){
if (data[leftmark] > pivot) break;
leftmark++;
}
while (rightmark > left){
if (data[rightmark] < pivot) break;
rightmark--;
}
if (leftmark > rightmark) break;
swap(&data[leftmark], &data[rightmark]);
}
swap(&data[left], &data[rightmark]);
quick_sort(data, left, rightmark - 1);
quick_sort(data, rightmark + 1, right);
}
Lab 快速排序 (Quick Sort) 4/5
32
left right
pivot
leftmark rightmark
leftmark
rightmark
Make
each
day
count
 測試快速排序
void main(){
int n, i;
int *data;
printf("Number of data: ");
scanf("%d", &n);
data = (int *)malloc(n*sizeof(int));
printf("Numbers to be sorted: ");
for(i = 0; i < n; i++){
scanf("%d", &data[i]);
}
printf("n");
quick_sort(data, 0, n);
printf("Numbers Sorted: ");
for(i = 0; i < n; i++){
printf("%d ", data[i]);
}
}
Lab 快速排序 (Quick Sort) 5/5
33
Make
each
day
count
 有三根杆⼦A,B,C。A杆上有 N 個 (N>1) 穿孔圓盤,盤的尺寸由下
到上依次變小。要求按下列規則將所有圓盤移至 C 杆:
 每次只能移動⼀個圓盤
 大盤不能疊在小盤上面
 提示:可將圓盤臨時置於 B 杆,也可將從 A 杆移出的圓盤重新移回 A 杆,
但都必須遵循上述兩條規則
Lab 解河內塔 1/4
34
Make
each
day
count
 將⼀個N層河內塔由A桿移到C桿。依照上面的解法
 先將前N-1層的圓盤先移到B桿
 再將第N層的圓盤移到C桿
 將B桿上的圓盤全部移到C桿
Lab 解河內塔 2/3
35
Make
each
day
count
#include <stdio.h>
int time = 0;
int main(int argc, char** argv) {
int n;
printf("請輸入河內塔的高度:");
scanf("%d", &n);
hanoi(n, 'A', 'B', 'C');
return(0);
}
Lab 解河內塔 3/4
36
Make
each
day
count
void hanoi(int n, char A, char B, char C){
if (n == 1) {
printf(“%3d: 將圓盤 %d 從 %c 移到 %cn", ++time, n, A, C);
}
else {
hanoi(n - 1, A, C, B);
printf(“%3d: 將圓盤 %d 從 %c 移到 %cn", ++time, n, A, C);
hanoi(n - 1, B, A, C);
}
}
Lab 解河內塔 4/4
37
Make
each
day
count
 變數的有效範圍 (scope) 是指哪些程式碼可以存取此變數的值
 變數的生命期 (life cycle)是變數的值會保留多久
 C 程式如果擁有多個函式,變數在那裡宣告,決定變數的有效範圍及
生命期。C 語言的變數依照有效範圍可以分為兩種:
 區域變數 (local variables)
在程式區塊中宣告的變數是⼀種區域變數,例如:在函式中宣告的變數或
參數,區域變數只能在宣告的函式中使⽤,在函式之外的程式碼並不能存
取此變數。
 全域變數 (global variables)
在 C 程式檔的函式之外宣告的變數是⼀種全域變數,例如:在函式外宣告
變數,整個程式檔案都可以存取此變數,如果全域變數沒有指定初值,預
設值是 0
變數的有效範圍與生命期 1/8
38
Make
each
day
count
#include <stdio.h>
int x=10; //global x
int main(int argc, char** argv) {
int y = 20; //y local to block 1
...
for () {
int z = 30; //z local to block 2
...
}
}
void func(){
int x = 40; //x local to block 3
...
}
變數的有效範圍與生命期 2/8
39
1
2
3
Make
each
day
count
 在剛才的例⼦中,所有變數都由編譯器自動依據變數宣告的位置來決
定變數特性,稱為自動 (auto) 變數
 除了自動變數,C 語言還提供了另外三種變數類型
 static (靜態變數)
 extern (外部變數)
 register (暫存器變數)
變數的有效範圍與生命期 3/8
40
Make
each
day
count
 靜態變數
 當程式脫離區域變數所在之程式區塊時,區域變數就會被回收,下次進入
再進入該程式區塊時,會重新配置區域變數,因此,前⼀次區域變數的值
並不會被保留
 在區域變數宣告前加上 static 關鍵字,就成為區域靜態變數
 靜態區域變數有效範圍和區域變數相同,但生命期⼀直到程式結束為止,
因此,當程式脫離區域變數所在之程式區塊時,區域變數仍繼續存在,下
次進入再進入該程式區塊時,前⼀次的變數值仍保留不會消失
變數的有效範圍與生命期 4/8
41
Make
each
day
count
#include <stdio.h>
void myfunc() {
int x = 10; //區域變數
static int y = 10; //靜態區域變數
x++;
y++;
printf("x = %d, ty = %dn", x, y);
}
void main(int argc, char** argv) {
for (int i = 0; i < 5; i++)
myfunc();
}
變數的有效範圍與生命期 5/8
42
Make
each
day
count
 外部變數
 當⼀個檔案需要參⽤的全域變數不是放在自己的程式檔中,⽽是放在另⼀
個程式檔,該全域變數稱之為外部變數,此時,必須在自己的程式檔使⽤
extern 關鍵字宣告外部變數
變數的有效範圍與生命期 6/8
43
//程式檔file1.c
#include <stdio.h>
int g_x = 10; //全域變數
void main(int argc, char** argv) {
...
}
//程式檔file2.c
extern int g_x; //外部變數
void myfunc() {
...
}
Make
each
day
count
 全域靜態變數
 若程式檔中的全域變數不想開放給其它程式檔共⽤時,可在該全域變數前
加上 static 關鍵字,將該全域變數宣告為靜態全域變數
變數的有效範圍與生命期 7/8
44
//程式檔file1.c
#include <stdio.h>
int g_x = 10; //全域變數
static int sg_x = 10; //靜態全域變數
void main(int argc, char** argv) {
...
}
//程式檔file2.c
extern int g_x; //外部變數
extern int sg_x;
void myfunc() {
...
}
會產生連結錯誤
Make
each
day
count
 暫存器變數
 暫存器變數與自動變數的有效範圍與生命期都⼀樣,兩者不同的是自動變
數是存放在記憶體中,⽽暫存器變數是直接儲存在 CPU 的暫存器中,因
此存取速度較快
 在變數宣告前加上 register 關鍵字,就成為暫存器變數
變數的有效範圍與生命期 8/8
45

Weitere ähnliche Inhalte

Was ist angesagt?

Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manualnikshaikh786
 
Understanding storage class using nm
Understanding storage class using nmUnderstanding storage class using nm
Understanding storage class using nmmohamed sikander
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions imtiazalijoono
 
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORYCS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORYRadha Maruthiyan
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)Make Mannan
 
Lab. Programs in C
Lab. Programs in CLab. Programs in C
Lab. Programs in CSaket Pathak
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project FileDeyvessh kumar
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manualSANTOSH RATH
 
C tech questions
C tech questionsC tech questions
C tech questionsvijay00791
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rathSANTOSH RATH
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4MKalpanaDevi
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...ssuserd6b1fd
 

Was ist angesagt? (20)

Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Understanding storage class using nm
Understanding storage class using nmUnderstanding storage class using nm
Understanding storage class using nm
 
Functions
FunctionsFunctions
Functions
 
Programming Fundamentals Decisions
Programming Fundamentals  Decisions Programming Fundamentals  Decisions
Programming Fundamentals Decisions
 
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORYCS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
 
C lab excellent
C lab excellentC lab excellent
C lab excellent
 
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
 
Lab. Programs in C
Lab. Programs in CLab. Programs in C
Lab. Programs in C
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 
C program
C programC program
C program
 
VTU Data Structures Lab Manual
VTU Data Structures Lab ManualVTU Data Structures Lab Manual
VTU Data Structures Lab Manual
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manual
 
C tech questions
C tech questionsC tech questions
C tech questions
 
Arrays
ArraysArrays
Arrays
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
6. function
6. function6. function
6. function
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
 
C programs
C programsC programs
C programs
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 2 of 5 by...
 

Ähnlich wie C語言函式 (20)

functions
functionsfunctions
functions
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Functions
FunctionsFunctions
Functions
 
sodapdf-converted into ppt presentation(1).pdf
sodapdf-converted into ppt presentation(1).pdfsodapdf-converted into ppt presentation(1).pdf
sodapdf-converted into ppt presentation(1).pdf
 
Functions
FunctionsFunctions
Functions
 
C important questions
C important questionsC important questions
C important questions
 
Code optimization
Code optimization Code optimization
Code optimization
 
Code optimization
Code optimization Code optimization
Code optimization
 
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Task4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docxTask4output.txt 2  5  9 13 15 10  1  0  3  7 11 14 1.docx
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
 
Array Cont
Array ContArray Cont
Array Cont
 
functions
functionsfunctions
functions
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan Kumari
 
Vcs16
Vcs16Vcs16
Vcs16
 
fraction_math.c for Project 5 Program Design fraction.pdf
fraction_math.c for Project 5  Program Design  fraction.pdffraction_math.c for Project 5  Program Design  fraction.pdf
fraction_math.c for Project 5 Program Design fraction.pdf
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
3 Function & Storage Class.pptx
3 Function & Storage Class.pptx3 Function & Storage Class.pptx
3 Function & Storage Class.pptx
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
 
C Programming Example
C Programming Example C Programming Example
C Programming Example
 

Mehr von 吳錫修 (ShyiShiou Wu)

mbot2.0教學-陀螺儀與三軸加速計應用.pdf
mbot2.0教學-陀螺儀與三軸加速計應用.pdfmbot2.0教學-陀螺儀與三軸加速計應用.pdf
mbot2.0教學-陀螺儀與三軸加速計應用.pdf吳錫修 (ShyiShiou Wu)
 
mbot2.0教學-四路顏色感測器應用.pdf
mbot2.0教學-四路顏色感測器應用.pdfmbot2.0教學-四路顏色感測器應用.pdf
mbot2.0教學-四路顏色感測器應用.pdf吳錫修 (ShyiShiou Wu)
 
mbot2.0教學-mblock5開發mBot 2.0應用程式.pdf
mbot2.0教學-mblock5開發mBot 2.0應用程式.pdfmbot2.0教學-mblock5開發mBot 2.0應用程式.pdf
mbot2.0教學-mblock5開發mBot 2.0應用程式.pdf吳錫修 (ShyiShiou Wu)
 

Mehr von 吳錫修 (ShyiShiou Wu) (20)

mbot2.0教學-陀螺儀與三軸加速計應用.pdf
mbot2.0教學-陀螺儀與三軸加速計應用.pdfmbot2.0教學-陀螺儀與三軸加速計應用.pdf
mbot2.0教學-陀螺儀與三軸加速計應用.pdf
 
mbot2.0教學-使用makeblock雲服務.pdf
mbot2.0教學-使用makeblock雲服務.pdfmbot2.0教學-使用makeblock雲服務.pdf
mbot2.0教學-使用makeblock雲服務.pdf
 
mbot2.0教學-局域網路傳輸應用.pdf
mbot2.0教學-局域網路傳輸應用.pdfmbot2.0教學-局域網路傳輸應用.pdf
mbot2.0教學-局域網路傳輸應用.pdf
 
mbot2.0教學-四路顏色感測器應用.pdf
mbot2.0教學-四路顏色感測器應用.pdfmbot2.0教學-四路顏色感測器應用.pdf
mbot2.0教學-四路顏色感測器應用.pdf
 
mbot2.0教學-聲光控制應用.pdf
mbot2.0教學-聲光控制應用.pdfmbot2.0教學-聲光控制應用.pdf
mbot2.0教學-聲光控制應用.pdf
 
mbot2.0教學-光感測器與LED應用.pdf
mbot2.0教學-光感測器與LED應用.pdfmbot2.0教學-光感測器與LED應用.pdf
mbot2.0教學-光感測器與LED應用.pdf
 
mbot2.0教學-超音波感測應用.pdf
mbot2.0教學-超音波感測應用.pdfmbot2.0教學-超音波感測應用.pdf
mbot2.0教學-超音波感測應用.pdf
 
mbot2.0教學-移動控制.pdf
mbot2.0教學-移動控制.pdfmbot2.0教學-移動控制.pdf
mbot2.0教學-移動控制.pdf
 
mbot2.0教學-mblock5開發mBot 2.0應用程式.pdf
mbot2.0教學-mblock5開發mBot 2.0應用程式.pdfmbot2.0教學-mblock5開發mBot 2.0應用程式.pdf
mbot2.0教學-mblock5開發mBot 2.0應用程式.pdf
 
mbot2.0教學-組裝與測試.pdf
mbot2.0教學-組裝與測試.pdfmbot2.0教學-組裝與測試.pdf
mbot2.0教學-組裝與測試.pdf
 
Python元組,字典,集合
Python元組,字典,集合Python元組,字典,集合
Python元組,字典,集合
 
Python函式
Python函式Python函式
Python函式
 
Python串列資料應用
Python串列資料應用Python串列資料應用
Python串列資料應用
 
Python 迴圈作業
Python 迴圈作業Python 迴圈作業
Python 迴圈作業
 
Python分支作業
Python分支作業Python分支作業
Python分支作業
 
Python基本資料運算
Python基本資料運算Python基本資料運算
Python基本資料運算
 
建置Python開發環境
建置Python開發環境建置Python開發環境
建置Python開發環境
 
micro:bit加速度感測應用
micro:bit加速度感測應用micro:bit加速度感測應用
micro:bit加速度感測應用
 
C語言檔案處理
C語言檔案處理C語言檔案處理
C語言檔案處理
 
C語言列舉與聯合
C語言列舉與聯合C語言列舉與聯合
C語言列舉與聯合
 

Kürzlich hochgeladen

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Kürzlich hochgeladen (20)

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

C語言函式

  • 1. 函式  何謂函式  內建函式  自定函式  函式的參數與引數  遞迴函式  變數的有效範圍與生命期 Revised on June 28, 2021
  • 2. Make each day count  設計程式時,常會發現⼀些具有特定功能⽽⼜重複出現的程式片段, 將這樣的程式片段獨立出來,必要時給予⼀些參數就能呼叫執⾏使⽤, 如此⼀來,這個程式片段就可以成為⼀個可重複使⽤的程式單元,在 C 語言我們稱之為函式 (Function)  C 語言的函式分為兩類  系統內建函式 (Library Functions)  使⽤者自定函式 (User Defined Functions)  內建函式如同是⼀個「⿊盒⼦」(black box),我們不需要了解函式內 部的的程式設計細節,也無法做更改,只要知道給予怎樣的參數可以 得到什麼結果 何謂函式 1/2 2 黑盒子 函 式 介 面 呼叫函式(引數) 內建函式 個人程式
  • 3. Make each day count void sort(int[] data) { ... } ... sort(data1); ... sort(data2); ...  自定函式是使⽤者自己依需求整理程式碼所建立,可以隨發展需求調 整更改。良好的規劃與設計自定函式有以下好處  函式可以重複使⽤,提高生產力  將系統分割成多個程式單元,可以交付多人共同設計,不僅縮短程式開發 時間,也可以達到程式模組化的目的  有助於提高程式可讀性,也讓程式的除錯及維護更加容易 何謂函式 2/2 3 返回 自定函式 主程式
  • 4. Make each day count  C 語言的編譯器提供⼀個已定義好的函式庫集合稱為標準函式庫  在標準函式庫裡有:輸出入函式、數學運算函式、字元函式、字串函 式、轉換函式、檔案輸出入函式、時間函式、亂數函式等  每個內建函式的函式原型宣告都放在標頭檔 (header file) 內建函式 1/2 4 標頭檔 函式群 stdio.h printf, scanf, gets, puts, getchar, putchar, fclose, feof, fgets, fputs, fread, fopen, fwrite, rewind, abs stdlib.h atof, atoi, atol, log, itoa, pow, rand, random, randomize, srand string.h strcmp, strcpy, strcat, strlen, strtok ctype.h isalnum, isalpha, isdigit, ispunct, isspace math.h acos, asin, atan, atof, poly, ceil, cos, div, exp, floor, sin, sqrt, tan time.h time, gettime, getdate, settime, setdate io.h eof, open, close, filelength, write, read conio.h getche, getch, clrscr
  • 5. Make each day count  要使⽤內建函式,必須在程式開頭處使⽤ #include 前置指令含入內建函 式的標頭檔 #include <stdio.h> #include <math.h> #define PI 3.14159 void std_func(){ double r; int x; printf("n x:角度值 t r:弳度值 t sin tt csc"); printf("n========================================================"); for(x = 30; x <= 150; x += 30){ r = PI * (x / 180.0); printf("n %3d tt %.5f t %.5f t %.5f", x, r, sin(r), 1 / sin(r)); } } 內建函式 2/2 5
  • 6. Make each day count  人體PSI生理週期  體力 (physical) 週期  對應協調、體力、健康,出生日算起每23天為⼀週期  情緒 (sensitive) 波動週期  對應創造力、敏感性、心情、領悟力、洞察力,從出生日算起每28天為 ⼀週期  智力 (intellectual) 強弱週期  對應警覺性、分析力、邏輯性、記憶力、溝通能力,從出生日算起每33 天為⼀週期  PSI生理週期曲線始於基線位置 (0%),表示個體出生時的狀態 Lab 計算PSI 生理週期 1/4 6
  • 7. Make each day count #include <math.h> #include <time.h> #define PCYCLE 23 #define SCYCLE 28 #define ICYCLE 33 #define PI 3.14159 void psi_cycle(){ int days, pdays, sdays, idays; float punit, sunit, iunit; int year_start, month_start, day_start; int year_end, month_end, day_end; int y2, m2, d2; int y1, m1, d1; time_t nowtime; struct tm *timeinfo; printf("請輸入出生年月日(例1995-10-06):"); scanf("%d-%d-%d", &year_start, &month_start, &day_start); printf("生日是%d-%d-%dn", year_start, month_start, day_start); Lab 計算PSI 生理週期 2/4 7
  • 8. Make each day count //獲取操作當天的日期 time (&nowtime ); timeinfo = localtime (&nowtime ); month_end = 1 + timeinfo->tm_mon; //月份值是0-11, 所以要加1 year_end = 1900 + timeinfo->tm_year; //年份起始值是1900,所以要加1900 day_end = timeinfo->tm_mday; //當月的日期值 printf("今天是%d-%d-%dn", year_end, month_end, day_end); //計算相隔天數。都換算為到0年3月1日的天數,再相減 m1 = (month_start + 9) % 12; y1 = year_start - m1/10; d1 = 365 * y1 + y1 / 4 - y1 / 100 + y1 / 400 + (m1 * 306 + 5) / 10 + (day_start - 1); m2 = (month_end + 9) % 12; y2 = year_end - m2 / 10; d2 = 365 * y2 + y2 / 4 - y2 / 100 + y2 / 400 + (m2 * 306 + 5) / 10 + (day_end - 1); days = d2 - d1; printf("相隔%d天n", days); Lab 計算PSI 生理週期 3/4 8
  • 9. Make each day count //計算PSI週期天數 pdays = days % PCYCLE; sdays = days % PCYCLE; idays = days % PCYCLE; //計算PSI週期值並顯示 punit = 2 * PI / PCYCLE; sunit = 2 * PI / SCYCLE; iunit = 2 * PI / ICYCLE; printf("體力時鐘週期處於%3.0f%%n", sin(pdays * punit) * 100); printf("情緒時鐘週期處於%3.0f%%n", sin(sdays * sunit) * 100); printf("智力時鐘週期處於%3.0f%%n", sin(idays * iunit) * 100); } Lab 計算PSI 生理週期 4/4 9
  • 10. Make each day count  自訂函式包括二個部份:函式原型宣告及函式定義  函式原型 (function prototype) 宣告  函式原型就是函式介面,目的在告知編譯器,程式中該如何使⽤該函式。 如果函式定義是在函式呼叫指令之後,必須在函式呼叫指令之前宣告函式 原型,否則會出現編譯錯誤  函式原型宣告語法如下: 傳回值資料型別 函式名稱(引數1資料型別, 引數2資料型別, …); double myfunc(int, int);  如果函式沒有回傳值,則在函式名稱前面加上 void;如果函式沒有引數, 則在函式名稱後面括弧內填入 void void myfunc(void);  雖然新版編譯器允許不宣告函式原型,對於良好撰寫風格的C程式碼來說, 函式⼀定要在使⽤前宣告 自訂函式 1/3 10
  • 11. Make each day count  函式定義 (function definition) 就是函式的程式區塊,語法如下:  例如: _Bool isPrime(int n) { for (i = 2; i <= sqrt(n); i++) { if (n % i == 0) break; } return (i > sqrt(n)); } 自訂函式 2/3 11 函式傳回值之資料型別, 若函式沒有傳回值則將ret_type指定為 void 自訂函式名稱 傳給函式的引數,其格式如同變數宣告; 如果沒有引數,則函式名稱後接空括號 指令敘述, 就是函式的實作 (implements) 有傳回值時,必須使用 return 敘述回傳資料
  • 12. Make each day count  呼叫函式  完成函式定義後,就可以將該函式當成⼀個新的指令敘述使⽤ _Bool isPrime(int); //函式原型宣告 int main(int argc, char* argv[]){ int num; printf("輸入整數值:"); scanf("%d", &num); if (isPrime(num)) printf("%d是質數", num); else printf("%d不是質數", num); } _Bool isPrime(int n){ for (i = 2; i <= sqrt(n); i++){ if (n % i == 0) break; } return (i > sqrt(n)); } 自訂函式 3/3 12 呼叫函式 返回主程式
  • 13. Make each day count  傳值呼叫 (call by value )  主程式把資料值複製⼀份給函式之引數保存 (另⼀個記憶體位置的值),因 此函式中不管如何存取引數資料,都不會影響到主程式的資料值 函式引數的傳遞方式 1/6 13 10 20 10 20 &num1 &a &num2 &b call_by_value(num1, num2); 主程式變數 函式引數 void call_by_value(int a,int b){ ... }
  • 14. Make each day count void swap_by_value(int a, int b){ int temp; printf("a = %d, b = %dn", a, b); temp = a; a = b; b = temp; printf("a = %d, b = %dn", a, b); } void main(){ int num1 = 10, num2 = 20; printf("num1 = %d, num2 = %dn", num1, num2); swap_by_value(num1, num2); printf("num1 = %d, num2 = %dn", num1, num2); } 函式引數的傳遞方式 2/6 14
  • 15. Make each day count  傳址呼叫 (call by address)  主程式把儲存資料的記憶體位置傳到函式之引數,因此引數與主程式是共 ⽤同⼀個記憶體位置之資料, void call_by_address(int* a, int* b){ ... } 函式引數的傳遞方式 3/6 15 10 20 &num1 &num2 &num1 &a &num2 &b call_by_address(&num1, &num2); 主程式變數 函式引數 *a *b &取址運算子:&num表示變數num的記憶體位址 *指標運算子:*a表示到變數a所指示的記憶體位址讀取資料 1 2 1 2
  • 16. Make each day count void swap_by_address(int* a, int* b){ int temp; printf("*a = %d, *b = %dn", *a, *b); temp = *a; *a = *b; *b = temp; printf("*a = %d, *b = %dn", *a, *b); } void main(){ int num1 = 10, num2 = 20; printf("num1 = %d, num2 = %dn", num1, num2); swap_by_address(&num1, &num2); printf("num1 = %d, num2 = %dn", num1, num2); } 函式引數的傳遞方式 4/6 16
  • 17. Make each day count  陣列資料傳遞  函式之間引數使⽤個別陣列元素,就與⼀般變數傳遞的情況⼀樣,為傳值 呼叫 void myFun(int, int); int main(int argc, char* argv[]) { int var1 = 10; int myArr[5] = {2, 5, 6, 4, 7}; myFun(var1, myArr[3]); } void myFun(int a, int b) { } 函式引數的傳遞方式 5/6 17 傳值 傳值
  • 18. Make each day count  函式之間引數使⽤整個陣列,則為傳址呼叫 void myFun(int, int[]); int main(int argc, char* argv[]) { int var1 = 10; int myArr[5] = {2, 5, 6, 4, 7}; myFun(var1, myArr); } void myFun(int a, int arr[]) { } 函式引數的傳遞方式 6/6 18 傳值 傳址
  • 19. Make each day count int bubble_sort(int data[], int n){ int i, j, flag, temp; for (i = 0; i < n - 1; i++){ //n個數字排序,只⽤n-1回合 flag = 0; //每回合清除交換旗號 for (j = 0; j < n – i - 1; j++) { if (data[j] > data[j + 1]) { temp = data[j]; data[j] = data[j + 1]; data[j + 1] = temp; flag = 1; //表示發生過交換 } } if (flag == 0) break; //此回合沒有發生交換,表示資料己排序 } } Lab 設計泡泡排序函式 1/2 19
  • 20. Make each day count  測試泡泡排序 void main(){ int n, i; int *data; printf("Number of data: "); scanf("%d", &n); data = (int *)malloc(n * sizeof(int)); printf("Numbers to be sorted: "); for(i = 0; i < n; i++) scanf("%d", &data[i]); printf("n"); bubble_sort(data, n); printf("Numbers Sorted: "); for(i = 0; i < n; i++) printf("%d ", data[i]); free(data); } Lab 設計泡泡排序函式 2/2 20
  • 21. Make each day count #include <stdio.h> void find_bound(int n, int data[], int *min, int *max){ //設計函式,從data[]找出最大值及最小值 } void main(){ int i, n, max, min, *data; printf("輸入資料個數:"); scanf("%d", &n); data = (int *)malloc(n * sizeof(int)); printf("輸入%d筆整數值(數值間以空白鍵區隔):", n); for (i = 0; i < n; i++) scanf("%d", &data[i]); find_bound(...); //呼叫find_bound()函式,...必須改為參數群 printf("最大值為%d%,最小值為%d", max, min); free(data); } 實作練習 設計尋找極值函式 1/2 21
  • 22. Make each day count  遞迴函式, 簡單地說就是⼀個呼叫自己的函式  計算 1 加到 N  疊代 (iterative) 方式 int sum(int n){ int i, sum = 0; for (i = 1; i <= n; i++) sum = sum + i; return sum; } 遞迴函式 (Recursive) 1/6 23
  • 23. Make each day count  遞迴 (recursive) 方式 int sum(int n){ if (n == 1) return 1; else return sum(n - 1) + n; }  要完成 sum(n) 的呼叫必須先完成 sum(n-1) 的呼叫,再把結果加上n,即 為 sum(n) 的結果;  ⽽要完成 sum(n-1),必須再呼叫 sum(n-2),先算出這個結果,再加上 n-1 就是 sum(n) 的結果了; 如此⼀直下去,直到呼叫 sum(1) 時函式很清楚地 知道結果為 1,於是立刻可以完成 sum(2)的呼叫,即 sum(1)+2 為 3;接下 去完成 sum(3) 的呼叫,得到 sum(2)+3 為 6,… 最後完成 sum(n) 的呼叫 遞迴函式 (Recursive) 2/6 24
  • 24. Make each day count 遞迴函式 (Recursive) 3/6 25 sum(10) sum(9) + 10 sum(8) + 9 sum(7) + 8 sum(6) + 7 sum(5) + 6 sum(4) + 5 sum(3) + 4 sum(2) + 3 sum(1) + 2 =1 45 55 3 6 10 15 21 28 36
  • 25. Make each day count  什麼樣的問題適合⽤遞迴函式來解決?  ⼀個問題如果可以拆解成規模較小但是性質和原問題完全⼀樣的問題的時 候, 就可以考慮⽤遞迴函式來處理  連加、連乘 (階乘)  輾轉相除  搜尋  排序  老鼠走迷宮  遞迴程式的結束  設計遞迴程式時,主體雖然是第 n 步驟和第 n-1 步驟之間的關係,但是⼀ 個非常容易忘掉的部份則是結束條件的測試 遞迴函式 (Recursive) 4/6 26
  • 26. Make each day count  費氏級數 (Fibonacci):𝑓 𝑛 𝑓 𝑛 1 𝑓 𝑛 2 ,𝑛 2 1 0 ,𝑛 1 ,𝑛 0  疊代 (iterative) 方式 int fib(int n){ int i, a1 = 0, a2 = 1, a3; if (n == 1) return 1; if (n == 0) return 0; for (i = 1; i < n; i++){ a3 = a1 + a2; a1 = a2; a2 = a3; } return a3; } 遞迴函式 (Recursive) 5/6 27
  • 27. Make each day count  遞迴 (recursive) 方式 int fibr(int n){ if (n == 1) return 1; if (n == 0) return 0; return fibr(n - 1) + fibr(n - 2); } 遞迴函式 (Recursive) 6/6 28 fibr(5) fibr(4) fibr(3) fibr(3) fibr(1) fibr(1) fibr(2) fibr(0) fibr(1) fibr(2) fibr(0) fibr(1) fibr(2) fibr(0) fibr(1) 1 0 0 0 1 1 1 1 2 2 1 1 1 3
  • 28. Make each day count  Quick Sort是⼀種「把大問題分成小問題處理 (Divide and Conquer)」 的方法,概念如下:  在數列中任意挑選⼀個數,稱為 pivot,然後調整數列,使得所有在 pivot 左邊的數,都比 pivot 還小,⽽在 pivot 右邊的數都比 pivot 大  接著,將所有在 pivot 左邊的數視為「新的數列」,所有在 pivot 右邊的 數視為「另⼀個新的數列」,「分別」重複上述步驟 (選 pivot、調整數 列),直到分不出「新的數列」為止  時間複雜度:平圴 O(NlogN) Lab 快速排序 (Quick Sort) 1/5 29
  • 29. Make each day count Lab 快速排序 (Quick Sort) 2/6 30 首先以 54 做為 pivot
  • 30. Make each day count  資料交換函式 void swap(int *a, int *b){ int temp; temp = *a; *a = *b; *b = temp; }  快速排序函式 void quick_sort(int data[], int left, int right){ int pivot, leftmark, rightmark; if (left >= right) return; pivot = data[left]; leftmark = left + 1; rightmark = right; Lab 快速排序 (Quick Sort) 3/5 31 left right pivot leftmark rightmark
  • 31. Make each day count while (1){ while (leftmark <= right){ if (data[leftmark] > pivot) break; leftmark++; } while (rightmark > left){ if (data[rightmark] < pivot) break; rightmark--; } if (leftmark > rightmark) break; swap(&data[leftmark], &data[rightmark]); } swap(&data[left], &data[rightmark]); quick_sort(data, left, rightmark - 1); quick_sort(data, rightmark + 1, right); } Lab 快速排序 (Quick Sort) 4/5 32 left right pivot leftmark rightmark leftmark rightmark
  • 32. Make each day count  測試快速排序 void main(){ int n, i; int *data; printf("Number of data: "); scanf("%d", &n); data = (int *)malloc(n*sizeof(int)); printf("Numbers to be sorted: "); for(i = 0; i < n; i++){ scanf("%d", &data[i]); } printf("n"); quick_sort(data, 0, n); printf("Numbers Sorted: "); for(i = 0; i < n; i++){ printf("%d ", data[i]); } } Lab 快速排序 (Quick Sort) 5/5 33
  • 33. Make each day count  有三根杆⼦A,B,C。A杆上有 N 個 (N>1) 穿孔圓盤,盤的尺寸由下 到上依次變小。要求按下列規則將所有圓盤移至 C 杆:  每次只能移動⼀個圓盤  大盤不能疊在小盤上面  提示:可將圓盤臨時置於 B 杆,也可將從 A 杆移出的圓盤重新移回 A 杆, 但都必須遵循上述兩條規則 Lab 解河內塔 1/4 34
  • 34. Make each day count  將⼀個N層河內塔由A桿移到C桿。依照上面的解法  先將前N-1層的圓盤先移到B桿  再將第N層的圓盤移到C桿  將B桿上的圓盤全部移到C桿 Lab 解河內塔 2/3 35
  • 35. Make each day count #include <stdio.h> int time = 0; int main(int argc, char** argv) { int n; printf("請輸入河內塔的高度:"); scanf("%d", &n); hanoi(n, 'A', 'B', 'C'); return(0); } Lab 解河內塔 3/4 36
  • 36. Make each day count void hanoi(int n, char A, char B, char C){ if (n == 1) { printf(“%3d: 將圓盤 %d 從 %c 移到 %cn", ++time, n, A, C); } else { hanoi(n - 1, A, C, B); printf(“%3d: 將圓盤 %d 從 %c 移到 %cn", ++time, n, A, C); hanoi(n - 1, B, A, C); } } Lab 解河內塔 4/4 37
  • 37. Make each day count  變數的有效範圍 (scope) 是指哪些程式碼可以存取此變數的值  變數的生命期 (life cycle)是變數的值會保留多久  C 程式如果擁有多個函式,變數在那裡宣告,決定變數的有效範圍及 生命期。C 語言的變數依照有效範圍可以分為兩種:  區域變數 (local variables) 在程式區塊中宣告的變數是⼀種區域變數,例如:在函式中宣告的變數或 參數,區域變數只能在宣告的函式中使⽤,在函式之外的程式碼並不能存 取此變數。  全域變數 (global variables) 在 C 程式檔的函式之外宣告的變數是⼀種全域變數,例如:在函式外宣告 變數,整個程式檔案都可以存取此變數,如果全域變數沒有指定初值,預 設值是 0 變數的有效範圍與生命期 1/8 38
  • 38. Make each day count #include <stdio.h> int x=10; //global x int main(int argc, char** argv) { int y = 20; //y local to block 1 ... for () { int z = 30; //z local to block 2 ... } } void func(){ int x = 40; //x local to block 3 ... } 變數的有效範圍與生命期 2/8 39 1 2 3
  • 39. Make each day count  在剛才的例⼦中,所有變數都由編譯器自動依據變數宣告的位置來決 定變數特性,稱為自動 (auto) 變數  除了自動變數,C 語言還提供了另外三種變數類型  static (靜態變數)  extern (外部變數)  register (暫存器變數) 變數的有效範圍與生命期 3/8 40
  • 40. Make each day count  靜態變數  當程式脫離區域變數所在之程式區塊時,區域變數就會被回收,下次進入 再進入該程式區塊時,會重新配置區域變數,因此,前⼀次區域變數的值 並不會被保留  在區域變數宣告前加上 static 關鍵字,就成為區域靜態變數  靜態區域變數有效範圍和區域變數相同,但生命期⼀直到程式結束為止, 因此,當程式脫離區域變數所在之程式區塊時,區域變數仍繼續存在,下 次進入再進入該程式區塊時,前⼀次的變數值仍保留不會消失 變數的有效範圍與生命期 4/8 41
  • 41. Make each day count #include <stdio.h> void myfunc() { int x = 10; //區域變數 static int y = 10; //靜態區域變數 x++; y++; printf("x = %d, ty = %dn", x, y); } void main(int argc, char** argv) { for (int i = 0; i < 5; i++) myfunc(); } 變數的有效範圍與生命期 5/8 42
  • 42. Make each day count  外部變數  當⼀個檔案需要參⽤的全域變數不是放在自己的程式檔中,⽽是放在另⼀ 個程式檔,該全域變數稱之為外部變數,此時,必須在自己的程式檔使⽤ extern 關鍵字宣告外部變數 變數的有效範圍與生命期 6/8 43 //程式檔file1.c #include <stdio.h> int g_x = 10; //全域變數 void main(int argc, char** argv) { ... } //程式檔file2.c extern int g_x; //外部變數 void myfunc() { ... }
  • 43. Make each day count  全域靜態變數  若程式檔中的全域變數不想開放給其它程式檔共⽤時,可在該全域變數前 加上 static 關鍵字,將該全域變數宣告為靜態全域變數 變數的有效範圍與生命期 7/8 44 //程式檔file1.c #include <stdio.h> int g_x = 10; //全域變數 static int sg_x = 10; //靜態全域變數 void main(int argc, char** argv) { ... } //程式檔file2.c extern int g_x; //外部變數 extern int sg_x; void myfunc() { ... } 會產生連結錯誤
  • 44. Make each day count  暫存器變數  暫存器變數與自動變數的有效範圍與生命期都⼀樣,兩者不同的是自動變 數是存放在記憶體中,⽽暫存器變數是直接儲存在 CPU 的暫存器中,因 此存取速度較快  在變數宣告前加上 register 關鍵字,就成為暫存器變數 變數的有效範圍與生命期 8/8 45