define PI 3 1415926 define Sr PIrr include

  • Slides: 13
Download presentation

计算机程序设计基础 清华大学计算机系 刘宝林 如:#define PI 3. 1415926 #define S(r) PI*r*r #include “stdio. h” void

计算机程序设计基础 清华大学计算机系 刘宝林 如:#define PI 3. 1415926 #define S(r) PI*r*r #include “stdio. h” void main( ) { float a, area; a=3. 6; area=S(a); printf(“r=%fnarea=%fn”, a, area); } 若定义#define S(r) PI*r*r,对area=S(a+b); 语句,置换后成为 area=PI*a+b; 这就不对了。所以,定义时应写成 #define S(r) PI*(r) S (a+b)=PI*(a+b) 7

计算机程序设计基础 清华大学计算机系 刘宝林 #define MAX(x, y) (x)>(y)? (x): (y) #include“stdio. h” 宏定义 void main(

计算机程序设计基础 清华大学计算机系 刘宝林 #define MAX(x, y) (x)>(y)? (x): (y) #include“stdio. h” 宏定义 void main( ) { int a, b, c, d, t; int max(int x, int y) a=1; b=3; c=5; d=2; { int z; t=MAX(a+b, c+d) z=x>y? x: y; printf(“%dn”, t); return(z); } } #include“stdio. h” void main( ) { int a, b, c, d, t; 函数调用 a=1; b=3; c=5; d=2; t=max(a+b, c+d); printf(“%dn”, t); } 9

计算机程序设计基础 清华大学计算机系 刘宝林 例1 有一个字符串,今输入一个字符,将该字符从字 符串中消去。 file 2. c file 1. c #include “file

计算机程序设计基础 清华大学计算机系 刘宝林 例1 有一个字符串,今输入一个字符,将该字符从字 符串中消去。 file 2. c file 1. c #include “file 2. c” #include“file 3. c” #include“file 4. c” void main( ) { char c; static char str[80]; enter_string(str); scanf(“%c”, &c); delete_string(str, c); print_string(str); } # include “stdio. h” enter_string(char str[80]) { gets(str); } file 3. c delete_string(char str[80], ch) { int i, j; for(i=j=0; str[i]!=‘’; i++) if(str[i]!=ch) str[j++]=str[i]; str[j]=‘’; } file 4. c #include “stdio. h” print_string(char str[80]) { printf(“%s”, str); } 11