290 likes | 594 Views
Overview Structure of a C program. Preprocessor directives ( 前置處理 ) Functions ( 函數 ) Remarks -- /* …; …;… */ or //…. ( 註解 ). //======================== // example to demo C structure // by ytlu Feb 25, 2005 // ========================
E N D
Overview Structure of a C program Preprocessor directives (前置處理) Functions (函數) Remarks -- /* …; …;… */ or //…. (註解)
//======================== // example to demo C structure // by ytlu Feb 25, 2005 // ======================== #include <stdio.h> #include <math.h> #include “ytlutable.h” double do_input(void); void do_output(double, double); int main() { double x, y, z; x = do_input(); y = MY_PI * x / 180.; z = cos(y) ; do _output(x, z); return(0); } double do_input() { double r; scanf(“%lf”,&r); return r; } void do_output(double p, double q) { printf(“cos(%lf) = %lf\n”,p,q); return; } ytlutable.h: #ifndef ytlu_table_ #define _ytlu_table_ #define _ytlu_table_ #define MY_Pi 3,1415926 #define MY_HBAR 6.24e-34 #define KB 1.38e-23 #endif Prepocessor directives main User-prepared include files placed in same directory with the executable function1 function2
Preprocessor Directives • #include <headfile> • #include “headfile” • #define symbolic values or functions • Declare global variables #include <stdio.h> // 包含庫存程式的定義檔 #define MATHPI 3.141592653589793 // 定義符號 #define CV(n, m) (n*ncol + m) // 定義符號函數 int ncol=3, nrow=4, ndim;// 宣告全域變數(函數)
Structure of a Function • Function’s type and name //函數名稱和型態 • Arguments passed in //傳遞的幅數 • Function body: //函數本體 • Variables declare //宣告變數 • Statements //工作指令 • Return value // 結果回傳
Function vlen() compute length of a vector double vlen(double x, double y, double z) // 函數名稱vlen型態double, 傳入三幅數x, y, z { double r2; // 宣告變數 r2 r2 = x * x + y * y + z * z; // 計算 r2 return(sqrt(r2)); //結果回傳 // 也可寫為 return sqrt(r2); }
Variable types • int a1, a2, a3; // 整數 • long int c1, c2, c3; // 長整數 • short int b1, b2, b3; // 短整數 • unsigned int ..; // 正整數 • unsigned long int …; // 4-byte 正整數 • float r1, r2, r3; // 4-bybe 浮點實數 • double d1, d2, d3; // 8-byte 浮點實數 • char acd, bch; // 單一字元
Constants (using suffix) • For example: a=4; b=1.23; • “4” is treated as an int, 1.23 as a double(the default types). // 預設 4 為整數, 1.23 為 8-byte 浮點實數 • Other type: a=4U;// unsigned int 正整數 b =8L;// long int 4-byte 整數 c = 1.23F;// float 4-byte 浮點 d = 1.2345L;// long double (10-byte)
Casting: (type)variable • Consider: int a=1, b=2; float c; c = a / b; printf(“c = %f\n”,c); • Result: c = 0.000000 • Why? (int)a/(int)c = (int)(0.5) = 0 • Correction: c = (float)a / (float)b;
Statements in a function(函數執行指令) • Variables declaration // 宣告變數 • Arithmetic expression // 算數運算 • Logic expression // 邏輯運算 • Loops // 迴圈 • Call other functions // 呼叫函數 -- Library functions or your own functions • Return value // 結果回傳
Arithmetic expression • Binary operators // 二元運算 = + - * / % *= += -= /= a *= b;// 等同 a = a*b; • Unary operators // 單元運算 n++; n--; -a n++;// 等同 n = n + 1;
Logic if statement Syntax: if ( condition ) { ………; ………; } elseif (condition2) { ………; ..……; } else if (condition3) {……..; ………;} else {…..; ……;}
Logic expressions (true=1 false=0) • a == b ; a != b • a > b ; a < b ; a <= b ; a >= b • && (and) eg. (( a > b) && (c <= d)) • || (or) eg. (( a > b) || (c > d)) if ( x > 0.0) { y = x * x; } else { y = 0.0; }
Repeating Loops Syntax: for (start; condition; step) { …….; …….; ……; } sum = 0; for (i = 0 ; i < 10 ; i++)sum = sum + i; for (i = 100 ; i > 0 ; i--) { j = i + 1; sum = sum + 1.0/(i*j); } for (i = 100; i > 0 ; i -= 2) sum = sum + 1.0/(i * ( i + 1)) ;
Libray functions and head files Headfile gives definitions of libray functions • stdio.h – defines scanf(), printf(), … • math.h – defines sin(), cos(), sqrt(), … • stdlib.h – defines system(“..”), rand(), atof(..),.. -- 編輯軟體所提供的 include 檔用 <…> -- 自己所編寫的 include 檔用 “…”, 必須放在執行檔所在的目錄下, 否則要把目錄包含在內. -- headfile only define 函數用法 (編輯用), 函數本身在 LIBRARY 目錄下以 .a (.o) 檔存在 (link 用)
Print to monitor (stdout) Syntax: printf(format string, variable list); Format: %c %d %e %f %s %u %lf %le printf(“i = %d j = %5d k = %2d\n”, I, j, k); printf(“cos(%lf) = %20.15lf\n”, x, cos(x)); printf(“exp(%lf) = %.15le\n”, x, exp(x)); Specail character: \n–new line
Input from keyboard (stdin) Syntax: scanf(format string, address list); Format: %c %d %f %h %s %lf %ld scanf(“%d %lf”, &n, &x); scanf(“%*s %lf %lf %lf”, &x, &y, &z);
Arithmetic functions #include <math.h> sinx = sin(x); // x in unit of radians cos(x) ; tan(x); acos(x); atan(x); asin(x) sqrt(x); abs(n); fabs(x); fmod(x, y) pow(x, y); exp(x); log(x); log10(x) cosh(x); sinh(x); tanh(x)
3 Program 001 • Write a c-code to check the following equality:
Frequently Appeared Errors • Typos: miss type, spelling error, ij,.. • Undeclared variables or functions. • Forget “;” at the end of a statement. • Unmatched delimiters: { }, “ “, ( ). • Unmatched arguments in calling a function. • Run-time error: a. typo i j within a loop control. b. logic error. c. problem related to mixed-type arithmetic.
Program 002 Taylor expansion: input x and n, then calculate exp(x). compare with that from math libray.
Guild to pratice 2 • Main() • Input double x • Pass x to function myexp(x) return value of exp(x) • Display the values of x and exp(x) • Double myexp(double x) • Initial tolerance, nlimit • Initila term = 1.0; sum = 1.0; • 3. Do loop ii = 1, to nlimit • Term = term *x / ii; • Sum = sum + term; • 6. If (fabs(term) < tolerance) break; • 7. Else repeat steps 4-6; • 8. Return sum
while(condition) { ; ;} do {..;..;} while(condition); int j ; double sum=0.0; for (j=1; j<100; j++) sum += 1.0/(doube)j; int j=1; double sum = 0.0; while (j<100) { sum += 1.0/(double)j ; j++; } int j=1; double sum = 0.0; do { sum += .0/(double)j; j++; } while(j <= 100);
Practice 1 separate from the main() the part for computing exp(x) expval(x, n) main() Input x and n Pass x and n Call expval(x, n) Calculate exp(x,n) Input a Return series sum Continue or not?
Practice 2: using reverse orderin summing Taylor series 1. initial summ = 1.0 2. a loop from j = n to j = 1 3. for each j do: summ = 1.0 + summ * x / j
Pratice 3 設計程式作下列工作: • 讀進一個 random seed, 用來 random 產生一個 0 – MAXIMUM 之間的整數. • 讓 user 猜 MAX_GUESS 數, 並提示所猜的太大或太小. • 輸出猜中, 或失敗訊息.
begin 輸入 seed Flow chart 流程圖 產生謎數 answer 猜答計數 ntry=0 輸入猜答 guess guess==answer? yes 輸出猜中信息 告之太大 no end 告之太小 計數 ntry+1 yes no answer>guess ntry >= MAX_TRY? yes no 輸出失敗信息
Functions needed void srand(unsigned int) :變化 random number 的產生 (defined in stdlib.h) int rand() :產生一個 random number (defined in stdlib.h) int scanf(“format”, addresses) : keyboard 輸入變數 (defined in stdio.h) int printf(“format”, variables) :寫到 monitor (define in stdio.h) Keywords of C unsigned int :宣告 unsigned 整數 while (logic expression) { }: while 控制迴圈 if (logic expression) {…} else if (logic expression) {…} else if (login expression) {…} % :兩整數除法得其餘數.