Repository: zhayujie/C-Primer-Plus Branch: master Commit: ca44759601bb Files: 178 Total size: 170.8 KB Directory structure: gitextract_25f3505s/ ├── .gitignore ├── C-Primer-Plus-6th-answer.doc ├── Chapter_01/ │ └── 1.c ├── Chapter_02/ │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ └── 8.c ├── Chapter_03/ │ ├── 2.c │ ├── 4.c │ ├── 5.c │ ├── 7.c │ └── 8.c ├── Chapter_04/ │ ├── 1.c │ ├── 2.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── 7.c │ └── 8.c ├── Chapter_05/ │ ├── 1.c │ ├── 2.c │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── 7.c │ ├── 8.c │ └── 9.c ├── Chapter_06/ │ ├── 1.c │ ├── 10.c │ ├── 11.c │ ├── 12.c │ ├── 13.c │ ├── 14.c │ ├── 15.c │ ├── 16.c │ ├── 17.c │ ├── 18.c │ ├── 2.c │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── 7.c │ ├── 8.c │ └── 9.c ├── Chapter_07/ │ ├── 1.c │ ├── 10.c │ ├── 11.c │ ├── 2.c │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── 7.c │ ├── 8.c │ └── 9.c ├── Chapter_08/ │ ├── 1.c │ ├── 2.c │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── 7.c │ └── 8.c ├── Chapter_09/ │ ├── 1.c │ ├── 10.c │ ├── 11.c │ ├── 2.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── 7.c │ ├── 8.c │ └── 9.c ├── Chapter_10/ │ ├── 1.c │ ├── 10.c │ ├── 11.c │ ├── 12.c │ ├── 13.c │ ├── 2.c │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── 7.c │ ├── 8.c │ └── 9.c ├── Chapter_11/ │ ├── 1.c │ ├── 10.c │ ├── 11.c │ ├── 12.c │ ├── 13.c │ ├── 14.c │ ├── 15.c │ ├── 16.c │ ├── 2.c │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── 7.c │ ├── 8.c │ └── 9.c ├── Chapter_12/ │ ├── 1.c │ ├── 2/ │ │ ├── pe12-2a.c │ │ ├── pe12-2a.h │ │ └── pe12-2b.c │ ├── 3/ │ │ ├── pe12-3a.c │ │ ├── pe12-3a.h │ │ └── pe12-3b.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── 7.c │ ├── 8.c │ └── 9.c ├── Chapter_13/ │ ├── 1.c │ ├── 10.c │ ├── 11.c │ ├── 12.c │ ├── 14.c │ ├── 2.c │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ ├── 7a.c │ ├── 7b.c │ ├── 8.c │ └── 9.c ├── Chapter_14/ │ ├── 1.c │ ├── 10.c │ ├── 11.c │ ├── 2.c │ ├── 3.c │ ├── 4a.c │ ├── 4b.c │ ├── 5.c │ ├── 6.c │ ├── 7.c │ ├── 8.c │ └── 9.c ├── Chapter_15/ │ ├── 1.c │ ├── 2.c │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ └── 7.c ├── Chapter_16/ │ ├── 2.c │ ├── 3.c │ ├── 4.c │ ├── 5.c │ ├── 6.c │ └── 7.c ├── Chapter_17/ │ ├── 1.c │ ├── 2movie/ │ │ ├── 2.c │ │ ├── movie.c │ │ └── movie.h │ ├── 3movie/ │ │ ├── 3.c │ │ ├── movie2.c │ │ └── movie2.h │ ├── 4queue/ │ │ ├── mall.c │ │ ├── queue.c │ │ └── queue.h │ ├── 5stack/ │ │ ├── 5.c │ │ ├── stack.c │ │ └── stack.h │ ├── 6.c │ ├── 7word/ │ │ ├── 7.c │ │ ├── word.c │ │ └── word.h │ └── 8pet/ │ ├── 8.c │ ├── pet.c │ └── pet.h └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Prerequisites *.d # Object files *.o *.ko *.obj *.elf # Linker output *.ilk *.map *.exp # Precompiled Headers *.gch *.pch # Libraries *.lib *.a *.la *.lo # Shared objects (inc. Windows DLLs) *.dll *.so *.so.* *.dylib # Executables *.exe *.out *.app *.i*86 *.x86_64 *.hex # Debug files *.dSYM/ *.su *.idb *.pdb # Kernel Module Compile Results *.mod* *.cmd .tmp_versions/ modules.order Module.symvers Mkfile.old dkms.conf # C Debug *.dsp *.dsw *.ncb *.opt *.plg # mac .DS_Store ================================================ FILE: Chapter_01/1.c ================================================ #include int main(void) { double inch, cm; printf("Please input the inches: "); scanf("%lf", &inch); cm = inch * 2.54; printf("%g cm\n", cm); return 0; } ================================================ FILE: Chapter_02/3.c ================================================ #include int main(void) { int days,years=21; days=years*365; printf("我的年龄是%d岁,%d天\n",years,days); return 0; } ================================================ FILE: Chapter_02/4.c ================================================ #include void jolly(void); void deny(void); int main(void) { jolly(); jolly(); deny(); return 0; } void jolly(void) { printf("For he's a jolly good fellow!\n"); } void deny(void) { printf("Which nobody can deny!\n"); } ================================================ FILE: Chapter_02/5.c ================================================ #include void br(void); void ic(void); int main(void) { br(); printf(","); ic(); printf("\n"); ic(); printf("\n"); br(); printf("\n"); return 0; } void br(void) { printf("Brazil,Russia"); } void ic(void) { printf("India,China"); } ================================================ FILE: Chapter_02/6.c ================================================ #include int main(void) { int toes=10; int toes_2,toes2; toes_2=2*toes; toes2=toes*toes; printf("toes是%d,toes的两倍是%d,toes的平方是%d\n",toes,toes_2,toes2); return 0; } ================================================ FILE: Chapter_02/8.c ================================================ #include void one_three(void); void two(void); int main(void) { printf("starting now\n"); one_three(); } void one_three(void) { printf("one\n"); two(); printf("three\n"); printf("done!\n"); } void two(void) { printf("two\n"); } ================================================ FILE: Chapter_03/2.c ================================================ #include int main(void) { char ch; printf("please input a number:"); scanf("%d",&ch); printf("%c\n",ch); return 0; } ================================================ FILE: Chapter_03/4.c ================================================ #include int main(void) { float a; printf("Enter a floating-point value: "); scanf("%f",&a); printf("fixed-point notation: %f\n",a); printf("exponential notation: %e\n",a); return 0; } ================================================ FILE: Chapter_03/5.c ================================================ #include int main(void) { int age; double seconds; printf("please input your age: "); scanf("%d",&age); seconds=age*3.156e7; printf("the corresponding seconds are: %e\n",seconds); return 0; } ================================================ FILE: Chapter_03/7.c ================================================ #include int main(void) { float inches,cms; printf("input your height(inch): "); scanf("%f",&inches); cms=inches*2.54; printf("your height(cm): %f\n",cms); return 0; } ================================================ FILE: Chapter_03/8.c ================================================ #include int main(void) { float pint,ounce,soupspoon,teaspoon,cup; printf("input the number of cups: "); scanf("%f",&cup); pint=cup/2; ounce=cup*8; soupspoon=ounce*2; teaspoon=soupspoon*3; printf("they are equivalent of:\n%f pint\n%f ounce\n%f soupspoons\n%f teaspoons\n",pint,ounce,soupspoon,teaspoon); return 0; } ================================================ FILE: Chapter_04/1.c ================================================ #include int main(void) { char firstname[40],lastname[40]; printf("Input your firstname: "); scanf("%s",firstname); printf("Input your lastname: "); scanf("%s",lastname); printf("Your name is %s,%s\n",firstname,lastname); return 0; } ================================================ FILE: Chapter_04/2.c ================================================ #include #include int main(void) { char name[40]; int width; printf("Input your name: "); scanf("%s",name); width=strlen(name)+3; printf("%*s\n",width,name); //输入的名和姓中间不能分隔 return 0; } ================================================ FILE: Chapter_04/4.c ================================================ #include int main(void) { float height; char name[40]; printf("Input your height(cm) and name: "); scanf("%f%s",&height,name); height=height/100; printf("%s, you are %.3fm tall\n",name,height); return 0; } ================================================ FILE: Chapter_04/5.c ================================================ #include int main(void) { float speed,size,time; printf("Input the download speed(Mb/s) and the file size(MB):\n"); scanf("%f%f",&speed,&size); time=size/speed*8.0; printf("At %.2f megabits per second, a file of %.2f megabytes\n",speed,size); printf("downloads in %.2f seconds.\n",time); return 0; } ================================================ FILE: Chapter_04/6.c ================================================ #include #include int main(void) { char firstname[40],lastname[40]; printf("Input your firstname: "); scanf("%s",firstname); printf("Input your lastname: "); scanf("%s",lastname); printf("%s %s\n",firstname,lastname); printf("%*d %*d\n", strlen(firstname),strlen(firstname),strlen(lastname),strlen(lastname)); printf("%s %s\n",firstname,lastname); printf("%*d %*d\n", -strlen(firstname),strlen(firstname),-strlen(lastname),strlen(lastname)); return 0; } ================================================ FILE: Chapter_04/7.c ================================================ #include #include int main(void) { double a=1.0/3.0; float b=1.0/3.0; printf("%.6f %.6f\n",a,b); //左侧double型 右侧float型 printf("%.12f, %.12f\n",a,b); printf("%.16f, %.16f\n",a,b); printf("DBL_DIG: %d\n",DBL_DIG); printf("FLT_DIG: %d\n",FLT_DIG); return 0; } ================================================ FILE: Chapter_04/8.c ================================================ #include #define GALLON 3.758 //1 gallon=3.785 liters #define MILE 1.609 //1 mile=1.609 kilometers int main(void) { float gallon,mile; printf("Input miles and gallons: "); scanf("%f%f",&mile,&gallon); printf("Miles per gallon: %.1f\n",mile/gallon); printf("Litre per 100 kilometers: %.1f\n", gallon*GALLON/(mile*MILE)*100); return 0; } ================================================ FILE: Chapter_05/1.c ================================================ #include #define H_P_M 60 //1h=60min int main(void) { int hour,min,left; printf("Enter the number of minutes: "); scanf("%d",&min); while(min>0) { hour=min/H_P_M; left=min%H_P_M; printf("%d minutes is %d hours and %d minutes.\n",min,hour,left); printf("Enter your next value: "); scanf("%d",&min); } printf("Good bye!\n"); return 0; } ================================================ FILE: Chapter_05/2.c ================================================ #include int main(void) { int num,count; printf("Input a integer: "); scanf("%d",&num); count=0; while(count++<11) { printf("%d ",num); num++; } printf("\n"); return 0; } ================================================ FILE: Chapter_05/3.c ================================================ #include #define DAYS_PER_WEEK 7 //一周7天 int main(void) { int day,week,left; printf("Input the number of days: "); scanf("%d",&day); while(day>0) { week=day/DAYS_PER_WEEK; left=day%DAYS_PER_WEEK; printf("%d days are %d weeks, %d days.\n",day,week,left); printf("Next input: "); scanf("%d",&day); } return 0; } ================================================ FILE: Chapter_05/4.c ================================================ #include #define CM_PER_FEET 30.48 //1feet=30.48cm #define CM_PER_INCH 2.54 //1inch=2.54cm int main(void) { int feet; float cm,inch; printf("Enter a height in centimeters: "); scanf("%f",&cm); while(cm>0) { feet=(int)(cm/CM_PER_FEET); inch=(cm-feet*CM_PER_FEET)/CM_PER_INCH; printf("%.1f cm = %d feet, %.1f inches\n",cm,feet,inch); printf("Enter a height in centimeters (<=0 to quit): "); scanf("%f",&cm); } printf("bye\n"); return 0; } ================================================ FILE: Chapter_05/5.c ================================================ #include int main(void) { int count,sum,days; printf("Input the number of days: "); scanf("%d",&days); count=sum=0; while(count++ int main(void) { int count,sum,days; printf("Input the number of days: "); scanf("%d",&days); count=sum=0; while(count++ void cube(double n); int main(void) { double num; printf("Input a number: "); scanf("%lf",&num); cube(num); } void cube(double n) { printf("The cube of %f is %f\n",n,n*n*n); } ================================================ FILE: Chapter_05/8.c ================================================ #include int main(void) { int num1,num2; printf("This program computes moduli.\n"); printf("Enter an integer to serve as the second operand: "); scanf("%d",&num1); printf("Now enter the first operand: "); scanf("%d",&num2); while(num2>0) { printf("%d %% %d is %d\n",num2,num1,num2%num1); printf("Enter next number for first operand (<= 0 to quit): "); scanf("%d",&num2); } printf("Done\n"); } ================================================ FILE: Chapter_05/9.c ================================================ #include void Temperatures(double fah); int main(void) { double fah,cel,kel;//华氏温度,摄氏温度,开氏温度 printf("Input the Fahrenheit temperature: "); while(scanf("%lf",&fah)==1) { Temperatures(fah); printf("Next input: "); } printf("Done.\n"); } void Temperatures(double fah) { const double a=5.0,b=9.0,c=32.0,d=276.13; printf("%.2f ℉ is %.2f ℃, %.2f K.\n", fah,a/b*(fah-c),a/b*(fah-c)+d); } ================================================ FILE: Chapter_06/1.c ================================================ #include #define SIZE 26 int main(void) { char ch[SIZE]; int index; for(index=0;index int main(void) { int lower, upper; int num, sum; printf("Enter lower and upper integer limits: "); scanf("%d%d", &lower, &upper); while (lower < upper) { for (sum=0, num=lower; num <= upper; num++) sum = sum + num * num; //计算平方和 printf("The sums of the squares from %d to %d is %d\n", lower * lower, upper * upper, sum); //输出结果 printf("Enter next set of limits: "); scanf("%d%d", &lower, &upper); //下一次输入 } printf("Done\n"); return 0; } ================================================ FILE: Chapter_06/11.c ================================================ #include #define SIZE 8 int main(void) { int num[SIZE]; int index; printf("Enter 8 integers: "); for (index=0; index= 0; index--) //倒序输出 printf("%d ", num[index]); printf("\n"); return 0; } ================================================ FILE: Chapter_06/12.c ================================================ #include int main(void) { double sum1=0, sum2=0; int count, items, sign; printf("Enter the items: "); scanf("%d", &items); //输入序列的项数 for (count=1, sign=1; count <= items; count++, sign *= -1) { sum1 += 1.0 / count; sum2 += 1.0 * sign / count; } //分别计算两序列的和 printf("1.0 + 1.0/2.0 + 1.0/3.0 + 1.0/4.0 + ... = %f\n", sum1); printf("1.0 - 1.0/2.0 + 1.0/3.0 - 1.0/4.0 + ... = %f\n", sum2); return 0; } ================================================ FILE: Chapter_06/13.c ================================================ #include #define SIZE 8 int main(void) { int index, count, num[SIZE]; for (index = 0, count = 1; index < SIZE; index++) { count *= 2; num[index] = count; } //for循环将数组元素设为2的前8次幂 index=0; //初始化index的值 do printf("%d ", num[index++]); while (index < SIZE); //do while循环显示数组元素的值 printf("\n"); return 0; } ================================================ FILE: Chapter_06/14.c ================================================ #include #define SIZE 8 int main() { double num1[SIZE], num2[SIZE]; int index1, index2, index; printf("Enter 8 numbers to the first array:\n"); for (index1 = 0; index1 < SIZE; index1++) scanf("%lf", &num1[index1]); //向第一个数组输入8个数 num2[0] = num1[0]; for (index1 = 1, index2 = 1; index1 < SIZE; index1++, index2++) num2[index2] = num2[index2-1] + num1[index1]; //为第二个数组赋值(是第一个数组对应的元素之和) printf("The first array: "); for (index=0; index < SIZE; index++) { printf("%6.2f", num1[index]); } //输出第一个数组的内容 printf("\nThe second array: "); for (index=0; index < SIZE; index++) { printf("%6.2f", num2[index]); //输出第二个数组的内容 } printf("\n"); return 0; } ================================================ FILE: Chapter_06/15.c ================================================ #include #include #define SIZE 255 int main(void) { int index; char ch[SIZE]; printf("Enter a line: "); for(index = 0, scanf("%c", &ch[0]); ch[index] != '\n';) { index++; scanf("%c", &ch[index]); } //输入内容到字符数组中,回车时结束 for(index += 1; index < SIZE; index++) ch[index] = '\0'; //将数组剩余空间补充为'\0' for(index = strlen(ch); index >=0; index--) printf("%c", ch[index]); //倒序输出内容 printf("\n"); return 0; } ================================================ FILE: Chapter_06/16.c ================================================ #include #define RATE_DAPHNE 0.1 #define RATE_DEIRDRE 0.05 //两人的利率 #define MONEY 100 int main(void) { int year; double daphne = MONEY, deirdre = MONEY; //两人的初始投资额相同 for (year = 1; daphne >= deirdre; year++) { daphne += MONEY * RATE_DAPHNE; deirdre += deirdre * RATE_DEIRDRE; } //计算Deirdre投资额超过Daphne需要的年数和当时的金额 printf("After %d year, Deirdre's investment will be more than Daphne's,\n" "Daphne's investment will be $%lf,\nand Deirdre's investment will be $%lf.\n", year, daphne, deirdre); //输出结果 return 0; } ================================================ FILE: Chapter_06/17.c ================================================ #include #define INITIAL_MONEY 100 //账户初始金额为100万元 #define ANNUAL_RATE 0.08 //年利率为8% int main(void) { int year; double money; for(year = 1, money=INITIAL_MONEY; money>0; year++) money += money * ANNUAL_RATE - 10; //计算每年年终的账户余额 printf("After %d years, Chuckie will draw all money from his account.\n", year); return 0; } ================================================ FILE: Chapter_06/18.c ================================================ #include #define INITIAL_NUMBER 5 //初始朋友数为5人 #define DUNBAR_NUMBER 150 //邓巴数 int main(void) { int week; int number = INITIAL_NUMBER; for (week = 1; number <= DUNBAR_NUMBER; week++) { number = (number - week) * 2; //计算每周的朋友数量 printf("After %d week, the number of Rabnud's friends is %d\n", week, number); } return 0; } ================================================ FILE: Chapter_06/2.c ================================================ #include int main(void) { int i,j; for(i=1;i<=5;i++) { for(j=1;j<=i;j++) printf("$"); printf("\n"); } return 0; } ================================================ FILE: Chapter_06/3.c ================================================ #include int main(void) { int i,j; for(i=1;i<=6;i++) { for(j=0;j #define ROWS 6 int main(void) { char ch; int i,j; for(ch='A',i=0;i int main(void) { char ch='A'; char a; int i, j,ROW; printf("please input a letter:"); scanf("%c", &a); ROW = a - ch + 1; for (i = 1; i <= ROW; i++) { for(j=1;j<=ROW-i;j++) printf(" "); for(j=0;j=0;j--) printf("%c",ch+j); printf("\n"); } return 0; } ================================================ FILE: Chapter_06/6.c ================================================ #include int main(void) { int max,min,num; printf("Input the min and max: "); scanf("%d%d",&min,&max); printf("%10s%10s%10s\n","number","square","cube"); for(num=min;num<=max;num++) printf("%10d%10d%10d\n",num,num*num,num*num*num); return 0; } ================================================ FILE: Chapter_06/7.c ================================================ #include #include #define WORD_SIZE 26 int main (void) { char word[WORD_SIZE]; printf("Input a word:\n"); scanf("%s", word); for(long i = strlen(word); i >= 0; i--) { printf("%c", word[i]); } printf("\n"); return 0; } ================================================ FILE: Chapter_06/8.c ================================================ #include int main(void) { double n1,n2; printf("Input two numbers: "); while(2==scanf("%lf%lf",&n1,&n2)) { printf("%f\n",(n1-n2)/n1*n2); printf("Input your next pair of numbers: "); } printf("Bye!\n"); return 0; } ================================================ FILE: Chapter_06/9.c ================================================ #include double calculate(double n1, double n2); int main(void) { double num1, num2; printf("Input two numbers: "); while (2 == scanf("%lf%lf", &num1, &num2)) //输入两个浮点数 { printf("%f\n", calculate(num1, num2)); //函数调用 printf("Input your next pair of numbers: "); } printf("Bye!\n"); return 0; } double calculate(double n1, double n2) { return ((n1 - n2) / (n1 * n2)); //返回运算结果 } ================================================ FILE: Chapter_07/1.c ================================================ #include int main(void) { char ch; int n_space = 0; //空格数 int n_newline = 0; //换行数 int n_others = 0; //其他字符数 printf("Enter some text; Enter # to quit.\n"); while ((ch = getchar()) != '#') { if (ch == ' ') n_space++; else if (ch == '\n') n_newline++; else n_others++; } printf("Spaces: %d, newlines: %d, others: %d\n", n_space, n_newline, n_others); return 0; } ================================================ FILE: Chapter_07/10.c ================================================ #include #define RATE1 0.15 #define RATE2 0.28 #define SINGLE 17850 //单身人群的税率分界点 #define HOST 23900 //户主人群的税率分界点 #define MAR_SHA 29750 //已婚共有人群的分界点 #define MAR_DEV 14875 //已婚离异人群的分界点 int main(void) { int num; double income, tax_break, tax; printpart: printf("Please enter Corresponding" "figures to select the type\n"); printf("1 single, 2 host, 3 married and shared, " "4 married but devoced and 5 to quit.\n"); scanf("%d", &num); switch (num) { case 1: tax_break = SINGLE; break; case 2: tax_break = HOST; break; case 3: tax_break = MAR_SHA; break; case 4: tax_break = MAR_DEV; break; case 5: printf("quit.\n"); return 0; default: printf("Please input right number."); goto printpart; //回到输入阶段 } printf("Enter your income: "); //指定种类和收入 while (scanf("%lf", &income) == 1) { if (income <= tax_break) tax = income * RATE1; else tax = tax_break * RATE1 + (income - tax_break) * RATE2; //计算税金 printf("The tax is $%.2lf.\n", tax); printf("Your next input: \n"); goto printpart; //回到输入阶段 } return 0; } ================================================ FILE: Chapter_07/11.c ================================================ #include #include #define ARTICHOKE 2.05 //洋蓟2.05美元/磅 #define BEET 1.15 //甜菜1.15美元/磅 #define CARROT 1.09 //胡萝卜1.09美元/磅 #define DISCOUNT_LIMIT 100 //包装费和运费打折要求订单100美元 #define DISCOUNT_RATE 0.05 //折扣为%5 #define BREAK1 5 #define BREAK2 20 //装运费的分界点 #define FEE1 6.5 #define FEE2 14 #define FEE3_RATE 0.5 //不同重量区间的装运费,其中超过20磅的每续重一磅 //增加0.5元 int main(void) { double weight; double weight_artichoke = 0; double weight_beet = 0; double weight_carrot = 0; //购买三种蔬菜的重量 double total_weight; //总重量 double veg_cost; //三种蔬菜总共花费 double order_cost; //订单总额 double total_cost; //费用总额 double pack_tran_fee; //装运费 double discount; int count = 0; char ch; printf("Please select the vegetables you want to buy:\n"); printf("a: artichoke $%.2f/lb\n", ARTICHOKE); printf("b: beet $%.2f/lb\n", BEET); printf("c: carrot $%.2f/lb\n", CARROT); printf("q: quit.\n"); //打印选择信息 while ((ch = tolower(getchar())) != 'q') { // if (ch == '\n') // continue; //滤掉回车 switch (ch) { case 'a': printf("Input the weight of artichoke in pound: "); scanf("%lf", &weight); weight_artichoke += weight; count++; printf("Continue entering a, b, c or q: "); break; case 'b': printf("Input the weight of beet in pound: "); scanf("%lf", &weight); weight_beet += weight; count++; printf("Continue entering a, b, c or q: "); break; case 'c': printf("Input the weight of carrot in pound: "); scanf("%lf", &weight); weight_carrot += weight; count++; printf("Continue entering a, b, c or q: "); break; default: printf("Please enter the right character."); } while (getchar () != '\n') continue; //滤掉输入重量后面的所有字符 } if (!count) { printf("Bye.\n"); return 0; } //开始输出q,直接退出 total_weight = weight_artichoke + weight_beet + weight_carrot; veg_cost = weight_artichoke * ARTICHOKE + weight_beet * BEET + weight_carrot * CARROT; discount = 0; if (veg_cost >= DISCOUNT_LIMIT) { discount = veg_cost * DISCOUNT_RATE; order_cost = veg_cost - discount; } else order_cost = veg_cost; //折扣计算 if (total_weight <= BREAK1) pack_tran_fee = FEE1; else if (total_weight <= BREAK2) pack_tran_fee = FEE2; else pack_tran_fee = FEE2 + (total_weight - BREAK2) * FEE3_RATE; //装运费计算 total_cost = order_cost + pack_tran_fee; printf("\nHere is what you choose:\n"); if (weight_artichoke) { printf("artichoke Price: $%.2f/lb weight: %.2f pounds cost: $%.2f\n", ARTICHOKE, weight_artichoke, weight_artichoke * ARTICHOKE); } if (weight_beet) { printf("beet Price: $%.2f/lb weight: %.2f pounds cost: $%.2f\n", BEET, weight_beet, weight_beet * BEET); } if (weight_carrot) { printf("carrot Price: $%.2f/lb weight: %.2f pounds cost: $%.2f\n", CARROT, weight_carrot, weight_carrot * CARROT); } printf("The order cost: $%.2f\n", veg_cost); if (discount) printf ("You have %%%.f discount, and the reduced money is $%.2f\n", DISCOUNT_RATE * 100, discount); printf("The packing and transpoting fee is $%.2f\n", pack_tran_fee); printf("The total cost is $%.2f\n", total_cost); //输出订单信息 return 0; } ================================================ FILE: Chapter_07/2.c ================================================ #include #define CHARS_PER_LINE 8 //每行字符数 int main(void) { char ch; int n_chars = 1; //字符数 printf("Enter some characters(# to quit):\n"); while ((ch = getchar()) != '#') { printf("%3c(%3d) ", ch, ch); if (n_chars++ % CHARS_PER_LINE == 0) printf("\n"); } printf("\n"); return 0; } ================================================ FILE: Chapter_07/3.c ================================================ #include int main(void) { int num; int n_even = 0, n_odd = 0; //偶数和奇数个数 int sum_even = 0, sum_odd = 0; //偶数和奇数和 printf("Enter some integers(0 to quit):\n"); scanf("%d", &num); while (num != 0) { if (num % 2 == 0) { n_even++; sum_even += num; } //计算偶数个数和偶数和 else { n_odd++; sum_odd +=num; } //计算奇数个数和奇数和 scanf("%d",&num); } printf("The number of even numbers is %d, " "and the everage of even numbers is %.2f\n", n_even, (n_even == 0) ? 0 : (float)sum_even / n_even); printf("The number of odd numbers is %d, " "and the everrage of odd numers is %.2f\n", n_odd, (n_odd == 0) ? 0 : (float)sum_odd / n_odd); return 0; } ================================================ FILE: Chapter_07/4.c ================================================ #include int main(void) { char ch; int n_repl = 0; //替换次数 printf("Enter some texts(# to quit):\n"); while ((ch = getchar()) != '#') { if (ch == '.') { ch = '!'; n_repl++; } //替换句号 else if (ch == '!') { printf("!"); n_repl++; } //替换感叹号 printf("%c", ch); } printf("\n%d substitutions were made.\n", n_repl); return 0; } ================================================ FILE: Chapter_07/5.c ================================================ #include int main(void) { char ch; int n_repl = 0; //替换次数 printf("Enter some texts(# to quit):\n"); while ((ch = getchar()) != '#') { switch (ch) { case '.': ch = '!'; n_repl++; break; case '!': printf("!"); n_repl++; break; default: break; } //利用switch语句进行替换 printf("%c",ch); } printf("\n%d substitutions were made.\n", n_repl); return 0; } ================================================ FILE: Chapter_07/6.c ================================================ #include int main(void) { char ch; char last_ch = 0; //前一个字符 int count=0; printf("Enter some texts(# to quit):\n"); while ((ch = getchar()) != '#') { if ((ch == 'i') && (last_ch == 'e')) count++; last_ch = ch; //出现ei时,计数+1 } printf("\"ei\" appeared %d times.\n", count); return 0; } ================================================ FILE: Chapter_07/7.c ================================================ #include #define BASE 1000 //基本工资 100美元/h #define TIME 40 //超过40h为加班 #define MUL 1.5 //加班时间算作平时的1.5倍 #define RATE1 0.15 //前300美元的税率 #define RATE2 0.2 //300-450美元的税率 #define RATE3 0.25 //大于450美元的税率 #define BREAK1 300 //税率的第一个分界点 #define BREAK2 450 //税率的第二个分界点 int main(void) { double hour, tax, gross; printf("Input your work hours in a week: "); scanf("%lf", &hour); if (hour <= TIME) gross = hour * BASE; else gross = TIME * BASE + (hour - TIME) * MUL * BASE; //计算总收入 if (gross <= BREAK1) tax = gross * RATE1; else if (gross <= BREAK2) tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2; else tax = BREAK1 * RATE1 + (BREAK2 - BREAK1) * RATE2 + (gross - BREAK2) * RATE3; //计算税金 printf("Your gross income is $%.2lf\nYour tax is $%.2lf\n" "Your net income is $%.2lf\n", gross, tax, (gross - tax)); return 0; } ================================================ FILE: Chapter_07/8.c ================================================ #include #define BASE1 8.75 #define BASE2 9.33 #define BASE3 10.00 #define BASE4 11.20 //四种等级的基本工资 #define TIME 40 //超过40h为加班 #define MUL 1.5 //加班时间算作平时的1.5倍 #define RATE1 0.15 //前300美元的税率 #define RATE2 0.2 //300-450美元的税率 #define RATE3 0.25 //大于450美元的税率 #define BREAK1 300 //税率的第一个分界点 #define BREAK2 450 //税率的第二个分界点 int main(void) { double base, hour, tax, gross; int count, num; const int LENGTH = 65; //*的长度 printpart: for (count = 0; count < LENGTH; count++) printf("*"); printf("\nEnter the number corresponding to the desired pay rate or action:\n"); printf("%-36s%s","1) $8.75/hr", "2) $9.33/hr\n"); printf("%-36s%s","3) $10.00/hr", "4) $11.20/hr\n"); printf("%s\n", "5) quit"); for (count = 0; count < LENGTH; count++) printf("*"); printf("\n"); //打印表格 while (scanf("%d", &num) == 1) { switch (num) { case 1: base = BASE1; break; case 2: base = BASE2; break; case 3: base = BASE3; break; case 4: base = BASE4; break; case 5: printf("quit.\n"); return 0; default: printf("Please input the right option.\n"); goto printpart; } //选择基本工资等级 printf("Input your work hours in a week: "); scanf("%lf", &hour); if (hour <= TIME) gross = hour * base; else gross = TIME * base + (hour - TIME) * MUL * base; //计算总收入 if (gross <= BREAK1) tax = gross * RATE1; else if (gross <= BREAK2) tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2; else tax = BREAK1 * RATE1 + (BREAK2 - BREAK1) * RATE2 + (gross - BREAK2) * RATE3; //计算税金 printf("Your gross income is $%.2lf\nYour tax is $%.2lf\n" "Your net income is $%.2lf\n", gross, tax, (gross - tax)); printf("\nYour next choice:\n"); } return 0; } ================================================ FILE: Chapter_07/9.c ================================================ #include int main(void) { int div, prime; int num, count; int flag; printf("Input a positive integer: "); scanf("%d", &num); printf("The prime numbers in range:\n"); for (prime = 2; prime <= num; prime++) //外层循环显示所有素数 { flag = 1; for (div = 2; (div * div) <= prime; div++) { if (prime % div == 0) flag = 0; } //内层循环检验是否为素数 if (flag) //利用标记flag判断 printf("%d ",prime); } printf("\n"); return 0; } ================================================ FILE: Chapter_08/1.c ================================================ #include int main(void) { int ch; int count = 0; while ((ch = getchar()) != EOF) count++; printf("The number of characters is %d\n", count); return 0; } ================================================ FILE: Chapter_08/2.c ================================================ #include #define SPACE 32 #define CTRL 64 #define COL 10 //每行打印10对 int main(void) { char ch; int count = 0; while ((ch = getchar()) != EOF) { count++; //打印字符输出 if (ch >= SPACE) printf("%c ", ch); //换行符和制表符的输出 else if (ch == '\n' || ch == '\t') printf("%s", ch == '\n' ? "\\n" : "\\t"); //一般控制字符的输出 else printf("^%c", ch + CTRL); printf("%-5d", ch); if (ch == '\n') count = 0; if (count % COL == 0) //10对换行 printf("\n"); } return 0; } ================================================ FILE: Chapter_08/3.c ================================================ #include #include int main(void) { int lower = 0, upper = 0; char ch; printf("Input some texts:\n"); while ((ch = getchar()) != EOF) { if (islower(ch)) lower++; if (isupper(ch)) upper++; } printf("lower:%d, upper:%d\n", lower, upper); return 0; } ================================================ FILE: Chapter_08/4.c ================================================ #include #include int main(void) { char ch; int inword = 0; //在单词中为1否则为0 int words = 0; //单词数 int chars = 0; //字符数 printf("Please enter some words:\n"); while ((ch = getchar()) != EOF) { if (!isspace(ch) && !ispunct(ch)) chars++; //开始一个新的单词 if (!isspace(ch) && !ispunct(ch) && !inword) { inword = 1; words++; } //单词末尾 if (isspace(ch) || ispunct(ch) && inword) inword = 0; } printf("There are %d words and %d letters\n", words, chars); printf("The average number of letters of "); printf("each word is %.2f.\n", ((double)chars / (double)words)); return 0; } ================================================ FILE: Chapter_08/5.c ================================================ #include #define LOW 1 //初始下限 #define HIGH 100 //初始上限 int get_guess(void); int main(void) { char response; int guess; int low = LOW; int high = HIGH; guess = (low + high) / 2; printf("Pick an integer from %d to %d. I will try to guess ", LOW, HIGH); printf("it.\nRespond with a y if my guess is right, with an s if it\n"); printf("is small and with a b if it is big.\n"); printf("Uh...is your number %d?\n", guess); while ((response = getchar()) != 'y') { if (response == 's') { low = guess; guess = (guess + high) / 2; } else if (response == 'b') { high = guess; guess = (guess + low) / 2; } else printf("Sorry, I understand only y, s and b.\n"); printf("Well, then, is it %d?\n", guess); //跳过剩余输入行 while (getchar() != '\n') continue; //使取值能到达上限 if (guess == HIGH - 1) guess++; } printf("I knew i could do it!\n"); return 0; } ================================================ FILE: Chapter_08/6.c ================================================ #include #include char get_first(void); int main(void) { char ch; while ((ch = get_first()) != EOF) { putchar(ch); printf("\n"); } return 0; } char get_first(void) { char ch; while (isspace(ch = getchar())) continue; while (getchar() != '\n') continue; return ch; } ================================================ FILE: Chapter_08/7.c ================================================ #include #define BASE1 8.75 #define BASE2 9.33 #define BASE3 10.00 #define BASE4 11.20 //四种等级的基本工资 #define TIME 40 //超过40h为加班 #define MUL 1.5 //加班时间算作平时的1.5倍 #define RATE1 0.15 //前300美元的税率 #define RATE2 0.2 //300-450美元的税率 #define RATE3 0.25 //大于450美元的税率 #define BREAK1 300 //税率的第一个分界点 #define BREAK2 450 //税率的第二个分界点 #define LENGTH 65 //*的长度 char get_choice(void); void calculate(double base); int main(void) { double base; char choice; while ((choice = get_choice()) != 'q') { switch (choice) { case 'a': base = BASE1; break; case 'b': base = BASE2; break; case 'c': base = BASE3; break; case 'd': base = BASE4; break; default: printf("Please respond with a, b, c, d or q.\n"); break; } if (choice >= 'a' && choice <= 'd') calculate(base); } return 0; } //计算和输出结果的函数 void calculate(double base) { double hour, gross, tax; printf("Input your work hours in a week: "); scanf("%lf", &hour); while (getchar() != '\n') continue; //跳过回车 if (hour <= TIME) gross = hour * base; else gross = TIME * base + (hour - TIME) * MUL * base; //计算总收入 if (gross <= BREAK1) tax = gross * RATE1; else if (gross <= BREAK2) tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2; else tax = BREAK1 * RATE1 + (BREAK2 - BREAK1) * RATE2 + (gross - BREAK2) * RATE3; //计算税金 printf("Your gross income is $%.2lf\nYour tax is $%.2lf\n" "Your net income is $%.2lf\n", gross, tax, (gross - tax)); printf("\n"); } //打印选择界面并让用户输入的函数 char get_choice(void) { char ch; int count; for (count = 0; count < LENGTH; count++) printf("*"); printf("\nEnter the letter corresponding to the desired pay rate or action:\n"); printf("%-36s%s","a) $8.75/hr", "b) $9.33/hr\n"); printf("%-36s%s","c) $10.00/hr", "d) $11.20/hr\n"); printf("%s\n", "q) quit"); for (count = 0; count < LENGTH; count++) printf("*"); printf("\n"); ch = getchar(); while (getchar() != '\n') continue; //跳过输出行剩余内容 return ch; } ================================================ FILE: Chapter_08/8.c ================================================ #include float get_float(void); char get_choice(void); char get_first(void); int main(void) { char choice; float num1, num2; while ((choice = get_choice()) != 'q') { printf("Enter first number: "); num1 = get_float(); printf("Enter second number: "); num2 = get_float(); switch (choice) { case 'a': printf("%.2f + %.2f = %.2f\n", num1, num2, num1 + num2); break; case 's': printf(".2%f - %.2f = %.2f\n", num1, num2, num1 - num2); break; case 'm': printf("%.2f * %.2f = %.2f\n", num1, num2, num1 * num2); break; case 'd': if (!num2) { printf("Enter a number other than 0: "); num2 = get_float(); } printf("%.2f / %.2f = %.2f\n", num1, num2, num1 / num2); break; default: printf("Program error!\n"); break; } } printf("Bye.\n"); return 0; } //打印界面和让用户选择的函数 char get_choice(void) { char ch; printf("Enter the operation of your choice:\n"); printf("%-36s%s\n", "a. add", "s. subtract"); printf("%-36s%s\n", "m. multiply", "d. divide"); printf("q. quit\n"); ch = get_first(); while (ch != 'a' && ch != 's' && ch != 'm' && ch != 'd' && ch != 'q') { printf("Please enter a, s, m, d or q.\n"); ch = get_first(); } return ch; } //获得输入值并处理错误输入的函数 float get_float(void) { float input; char ch; while (scanf("%f", &input) != 1) { while ((ch = getchar()) != '\n') putchar(ch); printf(" is not an number.\n"); printf("Please enter a number, such as 2.5, -1.78E8, or 3: "); } while (getchar() != '\n') continue; return input; } //读取输入行的第一个字符 char get_first(void) { char ch; ch = getchar(); while (getchar() != '\n') continue; return ch; } ================================================ FILE: Chapter_09/1.c ================================================ #include double min(double x, double y); int main(void) { double num1, num2; printf("Enter two numbers: "); scanf("%lf%lf", &num1, &num2); printf("The smaller one is: %f\n", min(num1, num2)); return 0; } double min(double n1, double n2) { return (n1 < n2 ? n1 : n2); } ================================================ FILE: Chapter_09/10.c ================================================ #include void to_base_n(unsigned long n, unsigned int base); int main(void) { unsigned long num; unsigned int base; printf("Enter an integer and the base from 2 to 10 (q to quit): "); while (scanf("%lu%u", &num, &base) == 2) { printf("Equivalent number on the base of %u: ", base); to_base_n(num, base); printf("\nEnter your next pair of numbers(q to quit): "); } printf("Done.\n"); return 0; } void to_base_n(unsigned long n, unsigned int base) { int r; r = n % base; if (n >= base) to_base_n(n / base, base); printf("%d", r); } ================================================ FILE: Chapter_09/11.c ================================================ #include unsigned long Fibonacci(unsigned n); int main(void) { unsigned int num; int count; printf("Input the number of the items (q to quit): "); while (scanf("%u", &num) == 1) { for (count = 1; count <= num; count++) printf("%lu ", Fibonacci(count)); printf("\nYour next input(q to quit): "); } printf("Bye.\n"); return 0; } unsigned long Fibonacci(unsigned n) { int count, temp; int n1 = 1, n2 = 1; if (n > 2) for (count = 3; count <= n; count++) { temp = n1 + n2; n1 = n2; n2 = temp; } else n2 = 1; return n2; } ================================================ FILE: Chapter_09/2.c ================================================ #include void chline(char ch, int i, int j); int main(void) { int row, col; char ch; printf("Input a character you want to print: "); ch = getchar(); printf("Input the number of rows and columns: "); scanf("%d%d", &row, &col); chline(ch, row, col); return 0; } void chline(char ch, int i , int j) { int row, col; for (row = 1; row <= i; row++) { for(col = 1; col <=j; col++) putchar(ch); putchar('\n'); } return; } ================================================ FILE: Chapter_09/4.c ================================================ #include double har_mean(double num1, double num2); int main(void) { double num1, num2; printf("Enter two numbers: "); scanf("%lf%lf", &num1, &num2); printf("The harmonic mean is: %f\n", har_mean(num1, num2)); } double har_mean(double num1, double num2) { return 1 / (1 / num1 + 1 / num2); } ================================================ FILE: Chapter_09/5.c ================================================ #include void larger_of(double * x, double * y); int main(void) { double num1, num2; printf("Input two numbers: "); scanf("%lf%lf", &num1, &num2); printf("Originally, num1 = %f, num2 = %f\n", num1, num2); larger_of(&num1, &num2); printf("Now, num1 = %f, num2 = %f\n", num1, num2); return 0; } void larger_of(double * x, double * y) { *x > *y ? (*y = *x) : (*x = *y); } ================================================ FILE: Chapter_09/6.c ================================================ #include void sort(double * x, double * y, double * z); int main(void) { double num1, num2 ,num3; printf("Enter 3 numbers: "); scanf("%lf%lf%lf", &num1, &num2, &num3); printf("Originally\nnum1 = %.2f, num2 = %.2f, num3 = %.2f\n", num1, num2, num3); sort(&num1, &num2, &num3); printf("Now\nnum1 = %.2f, num2 = %.2f, num3 = %.2f\n", num1, num2, num3); return 0; } void sort(double * x, double * y, double * z) { double temp; if (*y < *x) { temp = *y; *y = *x; *x = temp; } if (*z < *x) { temp = *z; *z = *x; *x = temp; } if (*z < *y) { temp = *z; *z = *y; *y = temp; } } ================================================ FILE: Chapter_09/7.c ================================================ #include #include int get_ch(char ch); int main(void) { char ch; printf("Input some texts:\n"); while ((ch = getchar()) != EOF) printf("%d ", get_ch(ch)); return 0; } int get_ch(char ch) { if (isalpha(ch)) return tolower(ch) - 'a' +1; else return -1; } ================================================ FILE: Chapter_09/8.c ================================================ #include double power(double n, int p); int main(void) { double x, xpow; int exp; printf("Enter a number and the interger power (q to quit):\n"); while (scanf("%lf%d", &x, &exp) == 2) { xpow = power(x, exp); printf("%.3g to the power %d is %g\n", x, exp, xpow); printf("Enter the next pair of numbers or q to quit.\n"); } printf("Bye.\n"); } double power(double n, int p) { int count; double pow = 1; if (p == 0) if (n == 0) { pow = 1; printf("It is not defined, so the value is treated as 1\n"); } else pow = 1; else if (p > 0) for (count = 0; count < p; count++) pow *= n; else if (n != 0) for (count = 0; count > p; count--) pow /= n; else pow = 0; return pow; } ================================================ FILE: Chapter_09/9.c ================================================ #include double power(double n, int p); int main(void) { double x, xpow; int exp; printf("Enter a number and the interger power (q to quit):\n"); while (scanf("%lf%d", &x, &exp) == 2) { xpow = power(x, exp); printf("%.3g to the power %d is %g\n", x, exp, xpow); printf("Enter the next pair of numbers or q to quit.\n"); } printf("Bye.\n"); } double power(double n, int p) { int count; double pow; if (p > 0) pow = n * power(n, p - 1); else if (p < 0) if (n != 0) pow = (1.0 / n) * power(n, p + 1); else pow = 0; else pow = 1; return pow; } ================================================ FILE: Chapter_10/1.c ================================================ #include #define MONTHS 12 //一年的月份数 #define YEARS 5 //一年的年数 int main(void) { //用2010~2014年的降水量数据初始化数组 const float rain[YEARS][MONTHS] = { {4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6}, {8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3}, {9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4}, {7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2}, {7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2} }; int year, month; float subtot, total; printf(" YEAR RAINFALL (inches)\n"); for (year = 0, total = 0; year < YEARS; year++) { //每一年,个月降水量总和 for (month = 0, subtot = 0; month < MONTHS; month++) subtot += *(*(rain + year) + month); printf("%5d %15.1f\n", 2010 + year, subtot); total += subtot; //5年的总降水量 } printf("\n The yearly average is %.1f inches.\n\n", total / YEARS); printf(" MONTHLY AVERAGES:\n\n"); printf(" Jan Feb Mar Apr May Jun Jul Aug Sep Oct "); printf(" Nov Dec\n"); for (month = 0; month < MONTHS; month++) { for (year = 0, subtot = 0; year < YEARS; year++) subtot += *(*(rain + year) +month); printf("%4.1f ", subtot / YEARS); } printf("\n"); return 0; } ================================================ FILE: Chapter_10/10.c ================================================ #include #define SIZE 4 void print_ar(double ar[], int n); //打印数组元素的函数 //将两个数组相加放入第三个数组的函数 void add_ar(double ar1[], double ar2[], double ar3[], int n); int main(void) { double ar1[SIZE] = {2, 4, 5, 8}; double ar2[SIZE] = {1, 0, 4, 6}; double ar3[SIZE]; printf("The first array: "); print_ar(ar1, SIZE); printf("The second array: "); print_ar(ar2, SIZE); add_ar(ar1, ar2, ar3, SIZE); printf("The third array: "); print_ar(ar3, SIZE); return 0; } void print_ar(double ar[], int n) { int i; for (i = 0; i < n; i++) printf("%g ", ar[i]); printf("\n"); } void add_ar(double ar1[], double ar2[], double ar3[], int n) { int i; for (i = 0; i < n; i++) ar3[i] = ar1[i] + ar2[i]; } ================================================ FILE: Chapter_10/11.c ================================================ #include #define ROWS 3 #define COLS 5 void change_ar(int ar[][COLS], int rows); //变化数组的函数 void print_ar(int ar[][COLS], int rows); //打印数组的函数 int main(void) { int array[ROWS][COLS] = { {1, 2, 6, 3, 3}, {6, 5, 2, 3, 2}, {7, 8, 7, 3, 6} }; printf("The original array:\n"); print_ar(array, ROWS); change_ar(array, ROWS); printf("The present array:\n"); print_ar(array, ROWS); return 0; } void change_ar(int ar[][COLS], int rows) { int r, c; for (r = 0; r < rows; r++) for (c = 0; c < COLS; c++) ar[r][c] *= 2; } void print_ar(int ar[][COLS], int rows) { int r, c; for (r = 0; r < rows; r++) { for (c = 0; c < COLS; c++) printf("%3d ", ar[r][c]); printf("\n"); } } ================================================ FILE: Chapter_10/12.c ================================================ #include #define MONTHS 12 //一年的月份数 #define YEARS 5 //一年的年数 void rainfall(float rain[][MONTHS], int years); int main(void) { //用2010~2014年的降水量数据初始化数组 const float rain[YEARS][MONTHS] = { {4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6}, {8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3}, {9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4}, {7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2}, {7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2} }; rainfall(rain, YEARS); return 0; } void rainfall(float rain[][MONTHS], int years) { float subtot, total; int y, m; printf(" YEAR RAINFALL (inches)\n"); for (y = 0, total = 0; y < years; y++) { //每一年,各月降水量总和 for (m = 0, subtot = 0; m < MONTHS; m++) subtot += rain[y][m]; printf("%5d %15.1f\n", 2010 + y, subtot); total += subtot; //5年的总降水量 } printf("\n The yearly average is %.1f inches.\n\n", total / YEARS); printf(" MONTHLY AVERAGES:\n\n"); printf(" Jan Feb Mar Apr May Jun Jul Aug Sep Oct "); printf(" Nov Dec\n"); for (m = 0; m < MONTHS; m++) { for (y = 0, subtot = 0; y < years; y++) subtot += rain[y][m]; printf("%4.1f ", subtot / years); } printf("\n"); } ================================================ FILE: Chapter_10/13.c ================================================ #include #define ROWS 3 #define COLS 5 #define NUM 15 //共计15个数 void get_num(double ar[][COLS], int rows); //把用户输入的数据储存在数组中 double aver_row(double ar[]); //计算每组数据的平均值 double aver_all(double ar[][COLS], int rows); //计算所有数据的平均值 double max_num(double ar[][COLS], int rows); //找出15个数据的最大值 //打印结果 void print_result(double ar[][COLS], int rows); int main(void) { double array[ROWS][COLS]; get_num(array, ROWS); print_result(array, ROWS); return 0; } void get_num(double ar[][COLS], int rows) { int r, c; double a = 1.0; //是为了让vc6.0编译器链接浮点链接库 printf("Please enter 3 groups of numbers, and there\n" "are 5 numbers in each group:\n"); for (r = 0; r < rows; r++) for (c = 0; c < COLS; c++) scanf("%lf", &ar[r][c]); } double aver_row(double ar[]) { int c; double sub; for (c = 0, sub = 0.0; c < COLS; c++) sub += ar[c]; return (sub / COLS); } double aver_all(double ar[][COLS], int rows) { int r, c; double total; for (r = 0, total = 0.0; r < rows; r++) for (c = 0; c < COLS; c++) total += ar[r][c]; return (total / NUM); } double max_num(double ar[][COLS], int rows) { int r, c; double max; for (r = 0, max = ar[0][0]; r < rows; r++) for (c = 0; c < COLS; c++) if (max < ar[r][c]) max = ar[r][c]; return max; } void print_result(double ar[][COLS], int rows) { int r, c, row; //打印数组 printf("The array:\n"); for (r = 0; r < rows; r++) { for (c = 0; c < COLS; c++) printf("%-5g", ar[r][c]); printf("\n"); } //输出每组平均值 for (row = 0; row #define SIZE 5 void copy_arr(double ar1[], double ar[], int n); void copy_ptr(double * ar2, double * ar, int n); void copy_ptrs(double * ar3, double * ar, double * end); void print_array(double ar[], int n); //打印数组的函数 int main(void) { double source[SIZE] = {1.1, 2.2, 3.3, 4.4, 5.5}; double target1[SIZE]; double target2[SIZE]; double target3[SIZE]; copy_arr(target1, source, SIZE); copy_ptr(target2, source, SIZE); copy_ptrs(target3, source, source + SIZE); print_array(target1, SIZE); print_array(target2, SIZE); print_array(target3, SIZE); return 0; } void copy_arr(double ar1[], double ar[], int n) { int index; for (index = 0; index < n; index++) ar1[index] = ar[index]; } void copy_ptr(double * ar2, double * ar, int n) { int i; for (i = 0; i < n; i++) *(ar2++) = *(ar++); } void copy_ptrs(double * ar3, double * ar, double * end) { int i; for (i = 0; ar < end; i++) *(ar3++) = *(ar++); } void print_array(double ar[], int n) { int index; for (index = 0; index < n; index++) printf("%g ", ar[index]); printf("\n"); } ================================================ FILE: Chapter_10/3.c ================================================ #include int max(int ar[], int n); int main(void) { int num[] = {23,2,32,66,3,5,25,7,3,20}; printf("The biggest number is %d\n", max(num, 10)); return 0; } int max(int ar[], int n) { int i, max; for (i = 0, max = ar[0]; i < n; i++) { if (max < ar[i]) max = ar[i]; } return max; } ================================================ FILE: Chapter_10/4.c ================================================ #include int max_index(double *ar, int n); int main(void) { double array[] = {1.5, 3.75, 4.3, 2.6, 2.15, 6.66}; printf("The index of the maximum number is: %d\n", max_index(array, 6)); return 0; } int max_index(double ar[], int n) { int i, max; for (max = 0, i = 1; i < n; i++) if (ar[max] < ar[i]) max = i; return max; } ================================================ FILE: Chapter_10/5.c ================================================ #include double gap(double ar[], int n); int main(void) { double array[] = {1.5, 3.75, 4.3, 2.6, 2.15, 6.66}; printf("The difference between the maximum and minimum " "values is:\n%g\n", gap(array, 6)); return 0; } double gap(double ar[], int n) { int i; double max, min; max = min = ar[0]; for (i = 0; i < n; i++) { if (max < ar[i]) max = ar[i]; if (min > ar[i]) min = ar[i]; } return (max - min); } ================================================ FILE: Chapter_10/6.c ================================================ #include #define SIZE 6 void reverse(double ar [], int n); void print_ar(double ar[], int n); //打印数组的函数 int main(void) { double array[] = {1.5, 3.75, 4.3, 2.6, 2.15, 6.66}; printf("The original array:\n"); print_ar(array, SIZE); reverse(array, SIZE); //使数据倒序排列 printf("The present array:\n"); print_ar(array, SIZE); return 0; } void reverse(double ar [], int n) { int i; double temp; for (i = 0; i < n / 2; i++) { temp = ar[i]; ar[i] = ar[n - i -1]; ar[n - i -1] = temp; } } void print_ar(double ar[], int n) { int i; for (i = 0; i < n; i++) printf("%g ", ar[i]); printf("\n"); } ================================================ FILE: Chapter_10/7.c ================================================ #include #define ROWS 3 #define COLS 2 void copy_ar(double ar1[], double ar[], int n); //拷贝数组的函数 void print_ar(double ar[][COLS], int rows); //打印数组的函数 int main(void) { int rows; double target[ROWS][COLS]; double source[ROWS][COLS] = { {1.2, 2.3}, {4.6, 5.2}, {7.8, 8.6} }; printf("The original array:\n"); print_ar(source, ROWS); for (rows = 0; rows < ROWS; rows++) copy_ar(target[rows], source[rows], COLS); printf("The copied array:\n"); print_ar(target, ROWS); return 0; } void copy_ar(double ar1[], double ar[], int n) { int index; for (index = 0; index < n; index++) ar1[index] = ar[index]; } void print_ar(double ar[][COLS], int rows) { int r, c; for (r = 0; r < rows; r++) { for (c = 0; c < COLS; c++) printf("%g ", ar[r][c]); printf("\n"); } } ================================================ FILE: Chapter_10/8.c ================================================ #include #define SIZE_SOU 7 //源数组元素个数 #define SIZE_TAR 3 //待拷贝元素个数 void copy_ptr(double * ar2, double * ar, int n); int main(void) { int i; double target[SIZE_TAR]; double souce[SIZE_SOU] = {1.5, 3.75, 4.3, 2.6, 2.15, 3.27, 6.66}; copy_ptr(target, souce + 2, SIZE_TAR); for (i = 0; i < SIZE_TAR; i++) printf("%g ", target[i]); printf("\n"); return 0; } void copy_ptr(double * ar2, double * ar, int n) { int i; for (i = 0; i < n; i++) *(ar2++) = *(ar++); } ================================================ FILE: Chapter_10/9.c ================================================ #include #define ROWS 3 #define COLS 5 void copy_ar(double ar1[][COLS], double ar[][COLS], int n); //拷贝数组的函数 void print_ar(double ar[][COLS], int rows); //打印数组的函数 int main(void) { double target[ROWS][COLS]; double source[ROWS][COLS] = { {1.2, 2.3, 2.6, 3.5, 3.2}, {4.6, 5.2, 2.8, 3.3, 2.1}, {7.8, 8.6, 7.2, 3.9, 6.6} }; printf("The original array:\n"); print_ar(source, ROWS); copy_ar(target, source, ROWS); printf("The copied array:\n"); print_ar(target, ROWS); return 0; } void copy_ar(double ar1[][COLS], double ar[][COLS], int rows) { int r, c; for (r = 0; r < rows; r++) for (c = 0; c < COLS; c++) ar1[r][c] = ar[r][c]; } void print_ar(double ar[][COLS], int rows) { int r, c; for (r = 0; r < rows; r++) { for (c = 0; c < COLS; c++) printf("%g ", ar[r][c]); printf("\n"); } } ================================================ FILE: Chapter_11/1.c ================================================ #include #define SIZE 40 char * gets_n(char ar[], int n); int main(void) { char str[SIZE]; gets_n(str, 10); puts(str); return 0; } char * gets_n(char ar[], int n) { int count = 0; while (count < n) ar[count++] = getchar(); ar[count] = '\0'; return ar; } ================================================ FILE: Chapter_11/10.c ================================================ #include #define SIZE 40 char * s_gets(char * st, int n); void delete_space(char * st); int main(void) { char str[SIZE]; while (*s_gets(str, SIZE) != '\n') delete_space(str); printf("Bye.\n"); return 0; } //删除空格的函数 void delete_space(char * st) { int i; char * p = st; printf("\nThe original string is:\n"); puts(st); while (*st) { //如果遇到空格,后面所有字符往前进一格 if (*st == ' ') for (i = 0; st[i] != '\0'; i++) st[i] = st[i + 1]; else st++; } printf("Now, the string is:\n"); puts(p); printf("\n"); } //自定义的字符串输入函数 char * s_gets(char * st, int n) { int i = 0; printf("Input the first string (blank line to quit):\n"); if (fgets(st, n, stdin) != NULL && st[0] != '\n') //即返回值st不等于NULL { while (st[i] != '\n' && st[i] != '\0') i++; if (st[i] == '\n') st[i] = '\0'; else while (getchar() != '\n') continue; } return st; } ================================================ FILE: Chapter_11/11.c ================================================ #include #include #include #define LIM 10 #define SIZE 80 char * s_gets(char * st, int n); //获取字符串输入 char get_choice(void); //获取选择 void print_sour(char * st[], int n); //打印源字符串 void print_ascii(char * st[], int n); //按ASCII码顺序打印 void print_length(char * st[], int n); //按长度顺序打印 void print_first_word(char * st[], int n); //按第一个单词的长度顺序打印 int first_word(char * st); //计算第一个单词数 int main(void) { char str[LIM][SIZE]; char * ptr[LIM]; int row = 0; //输入的字符串数量 char choice; //用户输入的选择字符 printf("Input some strings before EOF (no more than 10):\n"); while (row < LIM && s_gets(str[row], SIZE) != NULL) { ptr[row] = str[row]; //设置指针指向字符串 row++; } while((choice = get_choice()) != 'q') { printf("\n"); switch (choice) { case 'a': print_sour(ptr, row); break; case 'b': print_ascii(ptr, row); break; case 'c': print_length(ptr, row); break; case 'd': print_first_word(ptr, row); break; default: printf("Error!\n"); break; } printf("\n"); } printf("Bye.\n"); return 0; } //获取用户选择 char get_choice(void) { char ch; printf("a. print the sourse strings. b. print in order of ASCII.\n"); printf("c. print in order of length. d. print in order of the first word's length.\n"); printf("q. quit.\n"); printf("Enter a character (a, b, c, d or q):"); ch = getchar(); while (getchar() != '\n') continue; while (ch < 'a' || ch > 'd' && ch != 'q') { printf("Please input the right option (a, b, c, d or q): "); ch = getchar(); while (getchar() != '\n') continue; } return ch; } //打印源字符串 void print_sour(char * st[], int n) { int i; for (i = 0; i < n; i++) puts(st[i]); } //按ASCII中的顺序打印字符串 void print_ascii(char * st[], int n) { int i, j; char * temp; for (i = 0; i < n - 1; i++) for (j = i + 1; j < n; j++) if (strcmp(st[i], st[j]) > 0) { temp = st[j]; st[j] = st[i]; st[i] = temp; } for (i = 0; i < n; i++) puts(st[i]); } //按长度顺序打印 void print_length(char * st[], int n) { int i, j; char * temp; for (i = 0; i < n - 1; i++) for (j = i + 1; j < n; j++) if (strlen(st[i]) > strlen(st[j])) { temp = st[j]; st[j] = st[i]; st[i] = temp; } for (i = 0; i < n; i++) puts(st[i]); } //按第一个单词的长度顺序打印 void print_first_word(char * st[], int n) { int i, j; char * temp; for (i = 0; i < n - 1; i++) for (j = i + 1; j < n; j++) if (first_word(st[i]) > first_word(st[j])) { temp = st[j]; st[j] = st[i]; st[i] = temp; } for (i = 0; i < n; i++) puts(st[i]); } //计算第一个单词的长度 int first_word(char * st) { int i = 0; int count = 0; while (!isalpha(st[i])) i++; while (isalpha(st[i])) { i++; count++; } return count; } //自定义的输入函数 char * s_gets(char * st, int n) { int i = 0; if (fgets(st, n, stdin) != NULL) //即返回值st不等于NULL { while (st[i] != '\n' && st[i] != '\0') i++; if (st[i] == '\n') st[i] = '\0'; else while (getchar() != '\n') continue; return st; } else return NULL; } ================================================ FILE: Chapter_11/12.c ================================================ #include #include int main(void) { char ch; int word = 0, upper = 0, lower = 0; int punct = 0, digit = 0, inword = 0; while ((ch = getchar()) != EOF) { if (!isspace(ch) && (!ispunct(ch)) && !inword) { inword = 1; word++; } if (isspace(ch) || ispunct(ch) && inword) inword = 0; if (isupper(ch)) upper++; if (islower(ch)) lower++; if (ispunct(ch)) punct++; if (isdigit(ch)) digit++; } printf("words: %d, upper: %d, lower: %d, punct: %d, digit: %d.\n", word, upper, lower, punct, digit); return 0; } ================================================ FILE: Chapter_11/13.c ================================================ #include int main(int argc, char * argv[]) { int count; for (count = argc - 1; count > 0; count--) printf("%s ", argv[count]); return 0; } ================================================ FILE: Chapter_11/14.c ================================================ #include #include double mypower(double n, int exp); int main(int argc, char * argv[]) { printf("The result is: %g", mypower(atof(argv[1]), atoi(argv[2]))); } double mypower(double n, int exp) { double pow; if (exp > 0) for (pow = 1; exp > 0; exp--) pow *= n; else if (exp < 0) { if (!n) printf("It's not defined!\n"); for (pow = 1; exp < 0; exp++) pow *= (1 / n); } else if (n) pow = 1; else { pow = 1 / n; printf("It's not defined!\n"); } return pow; } ================================================ FILE: Chapter_11/15.c ================================================ #include #include int myatoi(char * st); int main(void) { char str[40]; gets(str); printf("%d\n", myatoi(str)); } int myatoi(char * st) { int sum = 0; while (*st) { //把字符数字逐位转化为数值 if (isdigit(*st)) sum = 10 * sum + (*st - '0'); else return 0; //不是纯数字则返回0 st++; } return sum; } ================================================ FILE: Chapter_11/16.c ================================================ #include #include #include #define SIZE 80 #define LIM 10 int main(int argc, char * argv[]) { int col; int i; int row = 0; char str[LIM][SIZE]; while (row < LIM && fgets(str[row], SIZE, stdin) != NULL) { if (argc == 1); else if (!strcmp(argv[1], "-p")); else if (!strcmp(argv[1], "-u")) for (col = 0; str[row][col] != '\0'; col++) str[row][col] = toupper(str[row][col]); else if (!strcmp(argv[1], "-l")) for (col = 0; str[row][col] != '\0'; col++) str[row][col] = tolower(str[row][col]); row++; } for (i = 0; i < row; i++) fputs(str[i], stdout); return 0; } ================================================ FILE: Chapter_11/2.c ================================================ #include #include #define SIZE 80 char * gets_n(char *ar, int n); int main(void) { char str[SIZE]; printf("Enter some characters:\n"); gets_n(str, 10); puts(str); return 0; } char * gets_n(char *ar, int n) { int i; for (i = 0; i < n; i++) { *(ar + i) = getchar(); if (isspace(*(ar + i))) break; } *(ar + i) = '\0'; return ar; } ================================================ FILE: Chapter_11/3.c ================================================ #include #include #define SIZE 40 void get_words(char * ar); int main(void) { char str[SIZE]; printf("Enter some characters:\n"); get_words(str); puts(str); return 0; } void get_words(char * ar) { char ch; while (isspace(ch = getchar())) continue; do *ar++ = ch; while (!isspace(ch = getchar())); *ar = '\0'; } ================================================ FILE: Chapter_11/4.c ================================================ #include #include #define SIZE 10 void get_words(char * ar, int n); int main(void) { char str[SIZE]; printf("Enter some characters:\n"); get_words(str, SIZE); puts(str); return 0; } void get_words(char * ar, int n) { char ch; int i = 0; while (isspace(ch = getchar())) continue; do { *(ar + i) = ch; i++; } while (!isspace(ch = getchar()) && i < (n - 1)); *(ar + i) = '\0'; } ================================================ FILE: Chapter_11/5.c ================================================ #include #include #define QUIT "quit" #define SIZE 80 //搜索字符在字符串中首次出现的位置 char * str_ch(char * str, char c); int main(void) { char str[SIZE]; char ch; char * ret_val; printf("Input a string (type quit to quit):\n"); gets(str); while (strcmp(str, QUIT)) { printf("Input a character: "); scanf("%c", &ch); while (getchar() != '\n') //跳过剩余输入部分 continue; ret_val = str_ch(str, ch); if (ret_val != NULL) printf("Find! The string start with the %c:\n" "%s\n", ch, ret_val); else printf("Can't find!\n"); printf("Input a string (type quit to quit):\n"); gets(str); } printf("Bye.\n"); return 0; } char * str_ch(char * str, char c) { int flag = 0; int count = 0; while (count++ < strlen(str)) if (*str++ == c) { flag = 1; break; } if (flag) return str - 1; else return NULL; } ================================================ FILE: Chapter_11/6.c ================================================ #include #include #define QUIT "quit" #define SIZE 80 //搜索字符在字符串中首次出现的位置 int is_within(char * str, char c); int main(void) { char str[SIZE]; char ch; printf("Input a string (type quit to quit):\n"); while (strcmp(gets(str), QUIT)) { printf("Input a character: "); scanf("%c", &ch); while (getchar() != '\n') //跳过剩余输入部分 continue; if (is_within(str, ch)) printf("Find!\n"); else printf("Can't find!\n"); printf("Input a string (type quit to quit):\n"); } printf("Bye.\n"); return 0; } int is_within(char * str, char c) { int flag = 0; size_t count = 0; while (count++ < strlen(str)) if (*str++ == c) { flag = 1; break; } return flag; } ================================================ FILE: Chapter_11/7.c ================================================ #include #include #define QUIT "quit" #define SIZE 40 char * mystrncpy(char * p1, char * p2, int n); int main(void) { char s1[SIZE]; char s2[SIZE]; int num; printf("Input the first string (type quit to quit):\n"); while (strcmp(gets(s1), QUIT)) //输入quit结束 { printf("Input the second string:\n"); gets(s2); printf("Input the number of char copied from s2: "); scanf("%d", &num); getchar(); //跳过回车 //当s2的长度大于或等于要拷贝的字符数时,要给s1末尾加上'\0', //并且注意要在调用函数之前,不然strlen(s1)会发生改变 if (strlen(s2) >= num) s1[strlen(s1) + num] = '\0'; puts(mystrncpy(s1, s2, num)); //输出拷贝后的字符串s1 printf("Input the first string (type quit to quit):\n"); } printf("Bye.\n"); } char * mystrncpy(char * p1, char * p2, int n) { int i = 1; char * p = p1; while (*p1++) continue; //p1指针指向位置已经超过空字符 *--p1 = *p2; while (i < n && *p2) { *++p1 = *++p2; i++; } return p; } ================================================ FILE: Chapter_11/8.c ================================================ #include #include #define SIZE 40 #define QUIT "quit" char * s_gets(char * st, int n); //读取字符串输入的函数 char * string_in(char * s1, char * s2); int main(void) { char str1[SIZE]; char str2[SIZE]; char * ret_val; printf("Input the first string (type quit to quit):\n"); while (strcmp(s_gets(str1, SIZE), QUIT)) //输入quit结束 { printf("Input the second string:\n"); s_gets(str2, SIZE); ret_val = string_in(str1, str2); if (ret_val) { printf("Find!\n"); puts(ret_val); } else printf("Can't find!\n"); printf("Input the first string (type quit to quit):\n"); } printf("Bye.\n"); } //自定义的字符串输入函数 char * s_gets(char * st, int n) { int i = 0; if (fgets(st, n, stdin)) //即返回值st不等于NULL { while (st[i] != '\n' && st[i] != '\0') i++; if (st[i] == '\n') st[i] = '\0'; else while (getchar() != '\n') continue; } return st; } //在s1中检测s2 char * string_in(char * s1, char * s2) { int i; while (*s1) { i = 0; while (s1[i] == s2[i]) { i++; if (!s2[i]) return s1; } s1++; } return NULL; } ================================================ FILE: Chapter_11/9.c ================================================ #include #include #define SIZE 40 #define QUIT "quit" char * s_gets(char * st, int n); void reverse(char * st); int main(void) { char str[SIZE]; while (strcmp(s_gets(str, SIZE), QUIT)) //输入quit结束 { reverse(str); puts(str); } return 0; } //自定义的字符串输入函数 char * s_gets(char * st, int n) { int i = 0; printf("Input the first string (type quit to quit):\n"); if (fgets(st, n, stdin)) //即返回值st不等于NULL { while (st[i] != '\n' && st[i] != '\0') i++; if (st[i] == '\n') st[i] = '\0'; else while (getchar() != '\n') continue; } return st; } //使字符串倒序的函数 void reverse(char * st) { unsigned int i; char temp; size_t length = strlen(st); for (i = 0; i < length / 2; i++) { temp = st[length - i -1]; st[length - i - 1] = st[i]; st[i] = temp; } st[length] = '\0'; } ================================================ FILE: Chapter_12/1.c ================================================ #include int critic(void); int main(void) { int units; printf("How many pounds to a firkin of butter?\n"); scanf("%d", &units); while (units != 56) units = critic(); printf("You must have looked it up!\n"); return 0; } int critic(void) { int answer; printf("No luck, my friend. Try again.\n"); scanf("%d", &answer); return answer; } ================================================ FILE: Chapter_12/2/pe12-2a.c ================================================ #include #include "pe12-2a.h" int main(void) { int mode; printf("Enter 0 for metric mode, 1 for US mode: "); scanf("%d", &mode); while (mode >= 0) { set_mode(mode); get_info(); show_info(); printf("Enter 0 for metric mode, 1 for US mode"); printf(" (-1 to quit): "); scanf("%d", &mode); } printf("Done.\n"); return 0; } ================================================ FILE: Chapter_12/2/pe12-2a.h ================================================ void set_mode(int mode); void get_info(void); void show_info(void); ================================================ FILE: Chapter_12/2/pe12-2b.c ================================================ #include static int last_mode; static double distance; static double fuel; void set_mode(int mode) { if (mode != 0 && mode != 1) { printf("Invalid mode specified. Mode %s used.\n", last_mode == 0 ? "0 (metric)" : "1 (US)"); } else last_mode = mode; } void get_info(void) { printf("Enter distance traveled in %s: ", last_mode == 0 ? "kilometers" : "miles"); scanf("%lf", &distance); printf("Enter fuel consumed in %s: ", last_mode == 0 ? "liters" : "gallons"); scanf("%lf", &fuel); } void show_info(void) { printf("Fuel consumption is "); if (last_mode == 0) printf("%.2f liters per 100 km.\n", fuel / distance * 100); else printf("%.1f miles per gallon.\n", distance / fuel); } ================================================ FILE: Chapter_12/3/pe12-3a.c ================================================ #include void get_info(int mode); int main(void) { int mode; printf("Enter 0 for metric mode, 1 for US mode: "); scanf("%d", &mode); while (mode >= 0) { get_info(mode); printf("Enter 0 for metric mode, 1 for US mode"); printf(" (-1 to quit): "); scanf("%d", &mode); } printf("Done.\n"); return 0; } ================================================ FILE: Chapter_12/3/pe12-3a.h ================================================ void set_mode(int mode); void get_info(void); void show_info(void); ================================================ FILE: Chapter_12/3/pe12-3b.c ================================================ #include int set_mode(int mode); void show_info(double * distance, double * fuel, int mode); int set_mode(int mode) { int last_mode = 0; if (mode != 0 && mode != 1) { printf("Invalid mode specified. Mode %s used.\n", last_mode == 0 ? "0 (metric)" : "1 (US)"); } else last_mode = mode; return last_mode; } void get_info(int mode) { double * p1, * p2; double distance, fuel; printf("Enter distance traveled in %s: ", set_mode(mode) == 0 ? "kilometers" : "miles"); scanf("%lf", &distance); printf("Enter fuel consumed in %s: ", set_mode(mode) == 0 ? "liters" : "gallons"); scanf("%lf", &fuel); p1 = &distance; p2 = &fuel; show_info(p1, p2, mode); } void show_info(double * distance, double * fuel, int mode) { printf("Fuel consumption is "); if (set_mode(mode) == 0) printf("%.2f liters per 100 km.\n", *fuel / *distance * 100); else printf("%.1f miles per gallon.\n", *distance / *fuel); } ================================================ FILE: Chapter_12/4.c ================================================ #include #define TIMES 20 void called_count(void); static int count; int main(void) { int i; for (i = 0; i < TIMES; i++) called_count(); printf("The times is %d.\n", count); } void called_count(void) { count++; } ================================================ FILE: Chapter_12/5.c ================================================ #include #include #include #define SIZE 100 void print_ar(int ar[], int n); //打印数组元素的函数 int main(void) { int i, j, temp; int digit[SIZE]; srand((unsigned int)time(0)); for (i = 0; i < SIZE; i++) { digit[i] = rand() % 10 + 1; } printf("The original numbers:\n"); print_ar(digit, SIZE); for (j = 0; j < SIZE - 1; j++) for (i = j + 1; i < SIZE; i++) if (digit[j] < digit[i]) { temp = digit[i]; digit[i] = digit[j]; digit[j] = temp; } printf("\nThe numbers in reverse order:\n"); print_ar(digit, SIZE); } void print_ar(int ar[], int n) { int i; for (i = 0; i < n; i++) { printf("%3d", ar[i]); if (i % 10 == 9) printf("\n"); } } ================================================ FILE: Chapter_12/6.c ================================================ #include #include #define SIZE 1000 #define SIZE_N 10 #define SIZE_S 10 int main(void) { int i, j; int count[SIZE_N]; //各随机数出现次数的数组 unsigned int seed[SIZE_S] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (j = 0; j < SIZE_S; j++) { for (i = 0; i < SIZE_N; i++) count[i] = 0; srand(seed[j]); printf("seed = %d:\n", seed[j]); for (i = 0; i < SIZE; i++) count[rand() % 10]++; for (i = 0; i < SIZE_N; i++) { printf("%d:%-5d ", i + 1, count[i]); if (i == 4) printf("\n"); } printf("\n"); } return 0; } ================================================ FILE: Chapter_12/7.c ================================================ #include #include #include void roll_count(int sets, int sides, int dice); int main(void) { int sets; int sides, dice; srand((unsigned int)time(0)); printf("Enter the number of sets; enter q to stop: "); while (scanf("%d", &sets) == 1) { printf("How many sides and how many dice? "); scanf("%d%d", &sides, &dice); printf("Here are %d sets of %d %d-sided throws.\n", sets, dice, sides); roll_count(sets, sides, dice); printf("How many sets? Enter q to stop: "); } printf("Bye.\n"); } void roll_count(int sets, int sides, int dice) { int i, j; int roll; if (sides < 2) { printf("Need at least 2 sides.\n"); return; } if (dice < 1) { printf("Need at least 1 die.\n"); return; } srand((unsigned int)time(0)); for (i = 0; i < sets; i++) { roll = 0; for (j = 0; j < dice; j++) roll += rand() % sides + 1; printf("%d ", roll); } printf("\n"); } ================================================ FILE: Chapter_12/8.c ================================================ #include #include int * make_array(int elem, int val); void show_array(const int ar [], int n); int main(void) { int * pa; int size; int value; printf("Enter the number of elements: "); while (scanf("%d", &size) == 1 && size > 0) { printf("Enter the initialization value: "); scanf("%d", &value); pa = make_array(size, value); if (pa) { show_array(pa, size); free(pa); } printf("Enter the number of elements (<1 to quit): "); } printf("Done.\n"); return 0; } int * make_array(int elem, int val) { int * pt; int i; pt = (int *)malloc(elem * sizeof(int)); for (i = 0; i < elem; i++) pt[i] = val; return pt; } void show_array(const int ar [], int n) { int i; for (i = 0; i < n; i++) { printf("%d ", ar[i]); if (i % 8 == 7) printf("\n"); } printf("\n"); } ================================================ FILE: Chapter_12/9.c ================================================ #include #include #include #define SIZE 40 char * * mal_ar(int n); int main(void) { int words, i; char * * st; printf("How many words do you wish to enter? "); scanf("%d", &words); getchar(); //滤掉回车 printf("Enter %d words now:\n", words); st = mal_ar(words); printf("Here are your words:\n"); for (i = 0; i < words; i++) { puts(st[i]); free(st[i]); //释放每个指针指向的内存 } free(st); //释放指针数组 return 0; } char * * mal_ar(int n) { char * * pt; int i, j; char ch; //给n个指针分配动态内存空间,返回指针的指针 pt = (char * *)malloc(n * sizeof(char *)); for (i = 0; i < n; i++) { //给每个指针指向的地址分配内存空间 pt[i] = (char *)malloc(SIZE * sizeof(char)); //可以仅用scanf("%s", pt[i]); while (isspace(ch = getchar())) //处理单词之前的空格符 continue; pt[i][0] = ch; //单词首字符 j = 1; while (!isspace(pt[i][j] = getchar())) j++; pt[i][j] = '\0'; //将末尾的空格替换为\0' } return pt; } ================================================ FILE: Chapter_13/1.c ================================================ #include #include #include #define SIZE 40 char * s_gets(char * st, int n); int main(void) { char name[SIZE]; char ch; unsigned long count = 0; FILE * fp; printf("Enter the file name: "); s_gets(name, SIZE); if ((fp = fopen(name, "r")) == NULL) { printf("Can't open %s\n", name); exit(EXIT_FAILURE); } while ((ch = getc(fp)) != EOF) { putc(ch, stdout); count++; } fclose(fp); printf("File %s has %lu characters\n", name, count); return 0; } //自定义读取文件名的函数 char * s_gets(char * st, int n) { char * find; char * ret_val; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); //查找换行符 if (find) *find = '\0'; //替换为空字符 else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_13/10.c ================================================ #include #include #define LEN 41 int main(void) { char name[LEN]; char words[LEN]; FILE * fp; long offset; //偏移量 printf("Please input the file name:\n"); gets(name); if ((fp = fopen(name, "r")) == NULL) { fprintf(stderr, "can't open \"%s\" file.\n", name); exit(EXIT_FAILURE); } printf("Please input a position in the file (negative number or " "Non numeric character to quit):\n"); while (scanf("%ld", &offset) == 1 && offset > 0) { getchar(); fseek(fp, offset, SEEK_SET); fscanf(fp, "%40s", words); fprintf(stdout, "%s\n", words); printf("Please input a position in the file (negative number or\n" "Non numeric character to quit):\n"); } fclose(fp); return 0; } ================================================ FILE: Chapter_13/11.c ================================================ #include #include #include #define SIZE 256 int main(int argc, char * argv[]) { FILE * fp; char words[SIZE]; if (argc < 3) { fprintf(stderr, "Wrong number of arguments.\n"); exit(EXIT_FAILURE); } if ((fp = fopen(argv[2], "r")) == NULL) { fprintf(stderr, "Could not open %s.", argv[2]); exit(EXIT_FAILURE); } while (fgets(words, SIZE, fp) != NULL) { if (strstr(words, argv[1]) != NULL) fputs(words, stdout); } if (fclose(fp) != 0) fprintf(stderr, "Error for closing file.\n"); return 0; } ================================================ FILE: Chapter_13/12.c ================================================ #include #include #define LEN 40 #define ROW 20 #define COL 30 int main(void) { FILE * fs, * fd; //fs指向源文件,fd指向目标文件 char name[LEN]; char digit[ROW][COL]; char result[ROW][COL + 1]; char ch[] = {" .':~*= %#"}; //数字字符对应的符号 int i, j; printf("Please enter the source file name:\n"); gets(name); //打开源文件 if ((fs = fopen(name, "r")) == NULL) { fprintf(stderr, "Could not open %s.", name); exit(EXIT_FAILURE); } //将文件内容读入 20 * 30 的int数组中 //并且转化成相应符号放入 20 * 31 的字符数组中 for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { fscanf(fs, "%d", &digit[i][j]); result[i][j] = ch[digit[i][j]]; } result[i][j] = '\0'; } printf("Enter the destination file name:\n"); gets(name); //打开目标文件 if ((fd = fopen(name, "w")) == NULL) { fprintf(stderr, "Could not open %s.", name); exit(EXIT_FAILURE); } //将结果打印出来并写入目标文件 for (i = 0; i < ROW; i++) { fprintf(stdout, "%s\n", result[i]); fprintf(fd, "%s\n", result[i]); } //关闭文件 if (fclose(fs) != 0 || fclose(fd) != 0) fprintf(stderr, "Error for closing file.\n"); return 0; } ================================================ FILE: Chapter_13/14.c ================================================ #include #include #include #define LEN 40 #define ROW 20 #define COL 30 int main(void) { FILE * fs, * fd; //fs指向源文件,fd指向目标文件 char name[LEN]; char dig[ROW][COL]; char res[ROW][COL + 1]; char ch[] = {" .':~*= %#"}; //数字字符对应的符号 int i, j; printf("Please enter the source file name:\n"); gets(name); //打开源文件 if ((fs = fopen(name, "r")) == NULL) { fprintf(stderr, "Could not open %s.", name); exit(EXIT_FAILURE); } //将文件内容读入 20 * 30 的int数组中 //并且转化成相应符号放入 20 * 31 的字符数组中 for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { fscanf(fs, "%d", &dig[i][j]); } } for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { if ((i == 0 && j == 0) || (i == 0 && j == 29) ||(i == 19 && j == 0) || (i == 19 && j == 29)) ; else if (i == 0) { if ((abs(dig[i][j] - dig[i][j - 1]) > 1) && (abs(dig[i][j] - dig[i][j + 1]) > 1) && (abs(dig[i][j] - dig[i + 1][j]) > 1)) dig[i][j] = (dig[i][j - 1] + dig[i][j + 1] + dig[i + 1][j]) / 3.0 + 0.5; } else if (j == 0) { if ((abs(dig[i][j] - dig[i - 1][j]) > 1) && (abs(dig[i][j] - dig[i][j + 1]) > 1) && (abs(dig[i][j] - dig[i + 1][j]) > 1)) dig[i][j] = (dig[i - 1][j] + dig[i][j + 1] + dig[i + 1][j]) / 3.0 + 0.5; } else if (i == 19) { if ((abs(dig[i][j] - dig[i][j - 1]) > 1) && abs((dig[i][j] - dig[i][j + 1]) > 1) && (abs(dig[i][j] - dig[i - 1][j]) > 1)) dig[i][j] = (dig[i - 1][j] + dig[i][j - 1] + dig[i][j + 1]) / 3.0 + 0.5; } else if (j == 29) { if ((abs(dig[i][j] - dig[i][j - 1]) > 1) && (abs(dig[i][j] - dig[i + 1][j]) > 1) && (abs(dig[i][j] - dig[i - 1][j]) > 1)) dig[i][j] = (dig[i - 1][j] + dig[i][j - 1] + dig[i + 1][j]) / 3.0 + 0.5; } else { if ((abs(dig[i][j] - dig[i][j - 1]) > 1) && (abs(dig[i][j] - dig[i][j + 1]) > 1) && (abs(dig[i][j] - dig[i - 1][j]) > 1) && (abs(dig[i][j] - dig[i + 1][j]) > 1)) dig[i][j] = (dig[i - 1][j] + dig[i + 1][j] + dig[i][j - 1] + dig[i][j + 1]) / 4.0 + 0.5; } } } for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { res[i][j] = ch[dig[i][j]]; } res[i][j] = '\0'; } printf("Enter the destination file name:\n"); gets(name); //打开目标文件 if ((fd = fopen(name, "w")) == NULL) { fprintf(stderr, "Could not open %s.\n", name); exit(EXIT_FAILURE); } //将结果打印出来并写入目标文件 for (i = 0; i < ROW; i++) { fprintf(stdout, "%s\n", res[i]); fprintf(fd, "%s\n", res[i]); } //关闭文件 if (fclose(fs) != 0 || fclose(fd) != 0) fprintf(stderr, "Error for closing file.\n"); return 0; } ================================================ FILE: Chapter_13/2.c ================================================ #include #include #define SIZE 256 int main(int argc, char * argv[]) { FILE * fs; //原始文件指针 FILE * fa; //目标文件指针 char temp[SIZE]; size_t bytes; //检查命令行参数 if (argc < 3) { fprintf(stderr, "Usage: %s filename\n", argv[0]); exit(EXIT_FAILURE); } //以读模式打开原始文件 if ((fs = fopen(argv[1], "rb")) == NULL) { fprintf(stderr, "I couldn't open the file \"%s\"\n", argv[1]); exit(EXIT_FAILURE); } //以读写模式打开目标文件 if ((fa = fopen(argv[2], "wb")) == NULL) { fprintf(stderr, "I couldn't open the file \"%s\"\n", argv[2]); exit(EXIT_FAILURE); } //拷贝数据 { while ((bytes = fread(temp, sizeof(char), SIZE, fs)) > 0) fwrite(temp, sizeof(char), bytes, fa); } fclose(fs); fclose(fa); return 0; } ================================================ FILE: Chapter_13/3.c ================================================ #include #include #include #define SIZE 40 char * s_gets(char * st, int n); int main(void) { FILE * fs; //原始文件指针 FILE * ft; //目标文件指针 char name_s[SIZE]; char name_t[SIZE]; char ch; //输入原始文件和目标文件名 fprintf(stdout, "Please enter the source file name:\n"); s_gets(name_s, SIZE); fprintf(stdout, "Please enter the target file name:\n"); s_gets(name_t, SIZE); //打开原始文件和目标文件 if ((fs = fopen(name_s, "r")) == NULL) fprintf(stderr, "Could not open the %s\n", name_s); if ((ft = fopen(name_t, "w")) == NULL) fprintf(stderr, "Could not open the %s\n", name_t); //拷贝数据 while ((ch = getc(fs)) != EOF) putc(toupper(ch), ft); fclose(fs); fclose(ft); return 0; } //自定义读取文件名的函数 char * s_gets(char * st, int n) { char * find; char * ret_val; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); //查找换行符 if (find) *find = '\0'; //替换为空字符 else while (getchar() != '\n') continue; //处理多余输入 } return ret_val; } ================================================ FILE: Chapter_13/4.c ================================================ #include #include int main(int argc, char * argv[]) { char ch; int i; FILE * fp; for (i = 1; i < argc; i++) { printf("File %d:\n", i); if ((fp = fopen(argv[i], "r")) == NULL) { fprintf(stderr, "Could not open %s.\n", argv[i]); exit(EXIT_FAILURE); } while ((ch = getc(fp)) != EOF) putchar(ch); printf("\n"); } return 0; } ================================================ FILE: Chapter_13/5.c ================================================ //命令行参数argv[1]代表目标文件名,后面几个为源文件名 //该程序把多个源文件加到源文件末尾 #include #include #include #define BUFSIZE 4096 #define SLEN 81 void append(FILE * source, FILE * dest); char * s_gets(char * st, int n); int main(int argc, char * argv[]) { FILE * fs, * fa; //fs指向源文件,fa指向目标文件 int i; int files = 0; char ch; if (argc < 3) { fprintf(stderr, "Usage: %s filename\n", argv[0]); exit(EXIT_FAILURE); } if ((fa = fopen(argv[1], "a+")) == NULL) { fprintf(stderr, "Could not open %s.\n", argv[1]); exit(EXIT_FAILURE); } if (setvbuf(fa, NULL, _IOFBF, BUFSIZE) != 0) { fputs("Can't creat output buffer\n", stderr); exit(EXIT_FAILURE); } for (i = 2; i < argc; i++) { if (strcmp(argv[1], argv[i]) == 0) { fputs("Can't append file to itself\n", stderr); } else if ((fs = fopen(argv[i], "r")) == NULL) { fprintf(stderr, "Could not open %s.\n", argv[i]); } else { if (setvbuf(fs, NULL, _IOFBF, BUFSIZE) != 0) { fputs("Can't creat input buffer\n", stderr); continue; } append(fs, fa); if (ferror(fs) != 0) fprintf(stderr, "Error in reading file %s.\n", argv[i]); if (ferror(fa) != 0) fprintf(stderr, "Error in writing file %s.\n", argv[1]); fclose(fs); printf("File %s appended.\n", argv[i]); } } printf("%s contents:\n", argv[1]); rewind(fa); while ((ch = getc(fa)) != EOF) putchar(ch); puts("Done displaying."); fclose(fa); return 0; } //附加文件的函数 void append(FILE * source, FILE * dest) { size_t bytes; static char temp[BUFSIZE]; while ((bytes = fread(temp, sizeof(char), BUFSIZE, source)) > 0) fwrite(temp, sizeof(char), bytes, dest); } //自定义读取文件名的函数 char * s_gets(char * st, int n) { char * find; char * ret_val; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); //查找换行符 if (find) *find = '\0'; //替换为空字符 else while (getchar() != '\n') continue; //处理多余输入 } return ret_val; } ================================================ FILE: Chapter_13/6.c ================================================ #include #include #include #define SIZE 40 char * s_gets(char * st, int n); int main(void) { FILE * fs, * fa; //fs指向源文件,fa指向目标文件 char ch; char name_source[SIZE]; char name_dest[SIZE]; int count = 0; //输入源文件和目标文件名 fprintf(stdout, "Please enter the source file name:\n"); s_gets(name_source, SIZE); fprintf(stdout, "Please enter the destination file name:\n"); s_gets(name_dest, SIZE); //打开源文件和目标文件 if ((fs = fopen(name_source, "r")) == NULL) { fprintf(stderr, "Could not open the %s\n", name_source); exit(EXIT_FAILURE); } if ((fa = fopen(name_dest, "w")) == NULL) { fprintf(stderr, "Could not open the %s\n", name_dest); exit(EXIT_FAILURE); } //将源文件每3个字符的第1个字符输出到目标文件 while ((ch = getc(fs)) != EOF) { if (count++ %3 == 0) putc(ch, fa); } //收尾工作 if (fclose(fs) != 0 || fclose(fa) != 0) fprintf(stderr, "Error in closing files\n"); return 0; } //自定义读取文件名的函数 char * s_gets(char * st, int n) { char * find; char * ret_val; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); //查找换行符 if (find) *find = '\0'; //替换为空字符 else while (getchar() != '\n') continue; //处理多余输入 } return ret_val; } ================================================ FILE: Chapter_13/7a.c ================================================ #include #include #include #define SIZE 40 #define SLEN 81 char * s_gets(char * st, int n); int main(void) { FILE * f1, * f2; char st[SLEN]; char name_f1[SIZE]; char name_f2[SIZE]; char * ret_val1; char * ret_val2; int count = 0; //依次输入两个文件的文件名 fprintf(stdout, "Please enter the first file name:\n"); s_gets(name_f1, SIZE); fprintf(stdout, "Please enter the second file name:\n"); s_gets(name_f2, SIZE); //依次输入两个文件 if ((f1 = fopen(name_f1, "r")) == NULL) { fprintf(stderr, "Could not open the %s\n", name_f1); exit(EXIT_FAILURE); } if ((f2 = fopen(name_f2, "r")) == NULL) { fprintf(stderr, "Could not open the %s\n", name_f2); exit(EXIT_FAILURE); } do { if ((ret_val1 = fgets(st, SLEN, f1)) != NULL) { fputs(st, stdout); } if ((ret_val2 = fgets(st, SLEN, f2)) != NULL) { fputs(st, stdout); } } while (ret_val1 != NULL || ret_val2 != NULL); fclose(f1); fclose(f2); return 0; } //自定义读取文件名的函数 char * s_gets(char * st, int n) { char * find; char * ret_val; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); //查找换行符 if (find) *find = '\0'; //替换为空字符 else while (getchar() != '\n') continue; //处理多余输入 } return ret_val; } ================================================ FILE: Chapter_13/7b.c ================================================ #include #include #include #define SIZE 40 #define SLEN 81 char * s_gets(char * st, int n); int main(void) { FILE * f1, * f2; char name_f1[SIZE]; char name_f2[SIZE]; char ch1, ch2; //依次输入两个文件的文件名 fprintf(stdout, "Please enter the first file name:\n"); s_gets(name_f1, SIZE); fprintf(stdout, "Please enter the second file name:\n"); s_gets(name_f2, SIZE); //依次输入两个文件 if ((f1 = fopen(name_f1, "r")) == NULL) { fprintf(stderr, "Could not open the %s\n", name_f1); exit(EXIT_FAILURE); } if ((f2 = fopen(name_f2, "r")) == NULL) { fprintf(stderr, "Could not open the %s\n", name_f2); exit(EXIT_FAILURE); } do { while ((ch1 = getc(f1)) != EOF && ch1 != '\n') { putchar(ch1); } while ((ch2 = getc(f2)) != EOF && ch2 != '\n') { putchar(ch2); } putchar('\n'); } while (ch1 != EOF || ch2 != EOF); fclose(f1); fclose(f2); return 0; } //自定义读取文件名的函数 char * s_gets(char * st, int n) { char * find; char * ret_val; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); //查找换行符 if (find) *find = '\0'; //替换为空字符 else while (getchar() != '\n') continue; //处理多余输入 } return ret_val; } ================================================ FILE: Chapter_13/8.c ================================================ #include #include int main(int argc, char * argv[]) { int i; char ch; FILE * fp; int count = 0; if (argc < 2) { fprintf(stderr, "the wrong number of arguments."); exit(EXIT_FAILURE); } if (argc == 2) { printf("Input some texts:\n"); while ((ch = getchar()) != EOF) { if (ch == argv[1][0]) count++; } printf("the \"%s\" in your input: %d times.", argv[1], count); } else { for (i = 2; i < argc; i++) { count = 0; if ((fp = fopen(argv[i], "r")) == NULL) { fprintf(stderr, "Could not open the %s.", argv[i]); continue; } while ((ch = getc(fp)) != EOF) { if (ch == argv[1][0]) count++; } fprintf(stdout, "the \"%s\" in %s: %d times.\n", argv[1], argv[i], count); } } return 0; } ================================================ FILE: Chapter_13/9.c ================================================ #include #include #include #define MAX 41 int main(void) { FILE * fp; char words[MAX]; char name[MAX]; int count = 0; printf("Please input the file name:\n"); gets(name); if ((fp = fopen(name, "a+")) == NULL) { fprintf(stderr, "can't open \"%s\" file.\n", name); exit(EXIT_FAILURE); } puts("Enter words to add to the file; press the #"); puts("key at the beginning of a line to terminate."); while ((fscanf(stdin, "%40s", words) == 1) && (words[0] != '#')) fprintf(fp, "%s\n", words); puts("File contents:"); rewind(fp); while (fscanf(fp, "%s", words) != EOF) { count++; fprintf(stdout, "%d. %s\n", count, words); } puts("Done!"); if (fclose(fp) != 0) fprintf(stderr, "Error closing file\n"); return 0; } ================================================ FILE: Chapter_14/1.c ================================================ #include #include #include #define NAMELEN 10 #define ABBLEN 4 #define MONTHS 12 char * s_gets(char * st, int n); int get_days(char * st); struct month { char name[NAMELEN]; char abbrev[ABBLEN]; int days; int monumb; }; struct month months[12] = { {"january", "jan", 31, 1}, {"february", "feb", 28, 2}, {"march", "mar", 31, 3}, {"april", "apr", 30, 4}, {"may", "may", 31, 5}, {"june", "jun", 30, 6}, {"july", "jul", 31, 7}, {"august", "aug", 31, 8}, {"september", "sep", 30, 9}, {"october", "oct", 31, 10}, {"november", "nov", 30, 11}, {"december", "dec", 31, 12} }; int main(void) { char st[NAMELEN]; printf("Please input the month name (empty line to quit):\n"); while (s_gets(st, NAMELEN) != NULL && st[0] != '\0') { if (get_days(st) == 0) printf("The month name is wrong.\n"); else printf("The days untill %s: %d\n", st, get_days(st)); printf("Next input (empty line to quit):\n"); } printf("Bye.\n"); return 0; } int get_days(char * st) { int total = 0; int i = 0; int count; while (st[i]) { st[i] = tolower(st[i]); i++; } for (i = 0; i < MONTHS; i++) { if (strcmp(st, months[i].name) == 0) break; } if (i < MONTHS) { for (count = 0; count <= i; count++) total += months[count].days; } return total; } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_14/10.c ================================================ #include #include #include #include #define LEN 81 #define SIZE 4 char * s_gets(char * st, int n); char get_choice(void); void ToUpper(char * st); void ToLower(char * st); void Transpos(char * st); void Dummy(char * st); int main(void) { char st[LEN]; char copy[LEN]; char ch; //函数指针数组 void(*fp[SIZE])(char *) = {ToUpper, ToLower, Transpos, Dummy}; int index; puts("Enter a string (empty line to quit):"); while (s_gets(st, LEN) != NULL && st[0] != '\0') { while ((ch = get_choice()) != 'q') { switch (ch) { case 'a': index = 0; break; case 'b': index = 1; break; case 'c': index = 2; break; case 'd': index = 3; break; default : printf("Program error.\n"); break; } strcpy(copy, st); (*(fp[index]))(copy); puts(copy); } printf("Enter a string (empty line to quit):\n"); } puts("Bye."); return 0; } char get_choice(void) { char ch; printf("To choose a function, enter its letter labal:\n"); printf("a). upper b). lower\n"); printf("c). transposed d). original\n"); printf("q). quit.\n"); while ((ch = getchar()) < 'a' || ch > 'd' && ch != 'q') { while (getchar() != '\n') continue; printf("Please input the right letter (a, b, c, d or q).\n"); } while (getchar() != '\n') continue; return ch; } void ToUpper(char * st) { while (*st) { *st = toupper(*st); st++; } } void ToLower(char * st) { while (*st) { *st = tolower(*st); st++; } } void Transpos(char * st) { while (*st) { if (islower(*st)) *st = toupper(*st); else if (isupper(*st)) *st = tolower(*st); st++; } } void Dummy(char * st) { } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_14/11.c ================================================ #include #include #define PSIZE 4 #define SIZE 100 void transform(double [], double [], int, double(*)(double)); double oppsite_val(double); double double_val(double); int main(void) { int i, j; double source[SIZE], target[SIZE]; double(*p[PSIZE])(double) = {sin, sqrt, oppsite_val, double_val}; printf("The source array:\n"); for (i = 0; i #include #include #define NAMELEN 10 #define ABBLEN 4 #define MONTHS 12 struct month { char name[NAMELEN]; char abbrev[ABBLEN]; int days; int monumb; }; struct month months[MONTHS] = { {"january", "jan", 31, 1}, {"february", "feb", 28, 2}, {"march", "mar", 31, 3}, {"april", "apr", 30, 4}, {"may", "may", 31, 5}, {"june", "jun", 30, 6}, {"july", "jul", 31, 7}, {"august", "aug", 31, 8}, {"september", "sep", 30, 9}, {"october", "oct", 31, 10}, {"november", "nov", 30, 11}, {"december", "dec", 31, 12} }; int get_res(void); void get_years(void); int get_months(void); int get_days(int); int main(void) { int total_days; total_days = get_res(); printf("The number of days before the specified day "); printf("is %d\n", total_days); return 0; } //得到结果的函数 int get_res(void) { int n_months; int n_days; int i; int total = 0; get_years(); n_months = get_months(); n_days = get_days(n_months); for (i = 0; i < n_months - 1; i++) { total += months[i].days; } total += n_days; return total; } //输入并处理年数 void get_years(void) { int n_years; printf("Please input a particular year: "); while (scanf("%d", &n_years) != 1) { while (getchar() != '\n') continue; printf("Please input a integer: "); } if (n_years % 4 == 0) months[1].days = 29; else months[1].days = 28; } //输入并处理月份 int get_months(void) { int n_months; printf("Input the month: "); while (scanf("%d", &n_months) != 1 || (n_months < 0 || n_months > 12)) { while (getchar() != '\n') continue; printf("Please input a integer from 1 to 12: "); } return n_months; } //输入并处理天数 int get_days(int n) { int n_days; printf("Input the days: "); while (scanf("%d", &n_days) != 1 || (n_days < 1 || n_days > months[n - 1].days)) { while (getchar() != '\n') continue; printf("Please input a integer from 1 to %d: ", months[n - 1].days); } return n_days; } ================================================ FILE: Chapter_14/3.c ================================================ #include #include #define MAXTITL 40 #define MAXAUTL 40 #define MAXBKS 100 struct book { char title[MAXTITL]; char author[MAXAUTL]; float value; }; void sort_by_input(const struct book library[], int n); void sort_by_title(struct book library[], int n); void sort_by_price(struct book library[], int n); char * s_gets(char * st, int n); int main(void) { static struct book library[MAXBKS]; int count = 0; printf("Please enter the book title (empty line to stop):\n"); while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL && library[count].title[0] != '\0') { printf("Now enter the author.\n"); s_gets(library[count].author, MAXTITL); printf("Now enter the value.\n"); scanf("%f", &library[count++].value); while (getchar() != '\n') continue; if (count < MAXBKS) printf("Enter the next title.\n"); } if (count > 0) { printf("The list of books in order of your input:\n"); sort_by_input(library, count); printf("The list of books in order of title:\n"); sort_by_title(library, count); printf("The list of books in order of price:\n"); sort_by_price(library, count); } return 0; } void sort_by_input(const struct book library[], int n) { int i; for (i = 0; i < n; i++) printf("%s by %s: $%.2f\n", library[i].title, library[i].author, library[i].value); printf("\n"); } void sort_by_title(struct book library[], int n) { int i, j; struct book temp; for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) if (strcmp(library[i].title, library[j].title) > 0) { temp = library[i]; library[i] = library[j]; library[j] = temp; } } for (i = 0; i < n; i++) printf("%s by %s: $%.2f\n", library[i].title, library[i].author, library[i].value); printf("\n"); } void sort_by_price(struct book library[], int n) { int i, j; struct book temp; for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) if (library[i].value > library[j].value) { temp = library[i]; library[i] = library[j]; library[j] = temp; } } for (i = 0; i < n; i++) printf("%s by %s: $%.2f\n", library[i].title, library[i].author, library[i].value); printf("\n"); } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_14/4a.c ================================================ #include #define SSN 20 #define LEN 10 struct names { char last_name[LEN]; char mid_name[LEN]; char fir_name[LEN]; }; struct person { char number[SSN]; struct names name; }; void print_info(struct person info[], int n); int main(void) { struct person info[5] = { {"B51414029", {"Jie", "Yu", "Zha"}}, {"B51414010", {"Xiang", "Xiang", "Pan"}}, {"B51414025", {"Jie", "Wen", "Jiang"}}, {"B51414031", {"Ming", "Cheng", "Liu"}}, {"B51414044", {"Qiang", " ", "Sha"}} }; print_info(info, 5); return 0; } void print_info(struct person info[], int n) { int i; for (i = 0; i < n; i++) { printf("%s, %s %c%c -- %s", info[i].name.last_name, info[i].name.fir_name, info[i].name.mid_name[0], (info[i].name.mid_name[0] == ' ') ? ' ': '.', info[i].number); printf("\n"); } } ================================================ FILE: Chapter_14/4b.c ================================================ #include #define SSN 20 #define LEN 10 struct names { char last_name[LEN]; char mid_name[LEN]; char fir_name[LEN]; }; struct person { char number[SSN]; struct names name; }; void print_info(struct person info); int main(void) { int index; struct person info[5] = { {"B51414029", {"Jie", "Yu", "Zha"}}, {"B51414010", {"Xiang", "Xiang", "Pan"}}, {"B51414025", {"Jie", "Wen", "Jiang"}}, {"B51414031", {"Ming", "Cheng", "Liu"}}, {"B51414044", {"Qiang", " ", "Sha"}} }; for (index = 0; index < 5; index++) print_info(info[index]); return 0; } void print_info(struct person info) { printf("%s, %s %c%c -- %s", info.name.last_name, info.name.fir_name, info.name.mid_name[0], (info.name.mid_name[0] == ' ') ? ' ': '.', info.number); printf("\n"); } ================================================ FILE: Chapter_14/5.c ================================================ #include #define LEN 10 #define NUM 3 #define CSIZE 4 #define N_SCORES 3 struct name { char first_name[LEN]; char last_name[LEN]; }; struct student { struct name names; float grade[NUM]; float average; }; void get_score(struct student info[], int n); void get_aver(struct student info[], int n); void print_info(struct student info[], int n); void get_all_aver(struct student info[], int n); int main(void) { struct student score[CSIZE] = { {{"Zha", "Yujie"}, {0, 0, 0}, 0}, {{"Jiang", "Wenjie"}, {0, 0, 0}, 0}, {{"Liu", "Chengming"}, {0, 0, 0}, 0}, {{"Pan", "Xiangxiang"}, {0, 0, 0}, 0} }; get_score(score, CSIZE); get_aver(score, CSIZE); print_info(score, CSIZE); get_all_aver(score, CSIZE); return 0; } void get_score(struct student info[], int n) { int i, j; for (i = 0; i < n; i++) { printf("Input the scores of 3 courses of %s %s\n", info[i].names.first_name, info[i].names.last_name); for (j = 0; j < N_SCORES; j++) { scanf("%f", &info[i].grade[j]); } } } void get_aver(struct student info[], int n) { int i, j; float sum; for (i = 0; i < n; i++) { for (j = 0, sum = 0.0; j < N_SCORES; j++) { sum += info[i].grade[j]; } info[i].average = sum / N_SCORES; } } void print_info(struct student info[], int n) { int i, j; printf(" Name%15s %s %s average\n", "score1", "score2", "score3"); for (i = 0; i < n; i++) { printf("%5s%-10s ", info[i].names.first_name, info[i].names.last_name); for (j = 0; j < N_SCORES; j++) printf("%6g", info[i].grade[j]); printf("%11.2f\n", info[i].average); } } void get_all_aver(struct student info[], int n) { int i; float total = 0; for (i = 0; i < n; i++) { total += info[i].average; } printf("The average score of all students is %.2f.\n", total / CSIZE); } ================================================ FILE: Chapter_14/6.c ================================================ #include #include #include #define LEN 10 #define NLEN 20 #define SIZE 20 struct member { int num; char fname[LEN]; char lname[LEN]; int play; int hit; int walk; int rbi; }; void get_initial_val(struct member *, int n); void get_data(struct member *, int n); void print_info(struct member *, int n); int main(void) { static struct member members[SIZE]; get_initial_val(members, SIZE); get_data(members, SIZE); print_info(members, SIZE); return 0; } void get_initial_val(struct member * pst, int n) { int i; for (i = 0; i < n; i++, pst++) { pst->num = 0; strcpy(pst->fname, ""); strcpy(pst->lname, ""); pst->play = 0; pst->hit = 0; pst->walk = 0; pst->rbi = 0; } } void get_data(struct member * pst, int n) { int number, play_times, hit_times, walk_times, rbi_num; FILE * fp; char name[NLEN]; char f_name[LEN], l_name[LEN]; printf("Please enter the file name: "); scanf("%s", name); if ((fp = fopen(name, "r")) == NULL) { fprintf(stderr, "Can't open %s\n", name); exit(EXIT_FAILURE); } while (fscanf(fp, "%d%s%s%d%d%d%d", &number, f_name, l_name, &play_times, &hit_times, &walk_times, &rbi_num) == 7) { pst[number].num = number; strcpy(pst[number].fname, f_name); strcpy(pst[number].lname, l_name); pst[number].play += play_times; pst[number].hit += hit_times; pst[number].walk += walk_times; pst[number].rbi += rbi_num; } fclose(fp); } void print_info(struct member * pst, int n) { int i; for (i = 0; i < n; i++) { if (pst[i].fname[0] != '\0') { printf("%d %s %s %d %d %d %d", pst[i].num, pst[i].fname, pst[i].lname, pst[i].play, pst[i].hit, pst[i].walk, pst[i].rbi); printf("\n"); } else break; } } ================================================ FILE: Chapter_14/7.c ================================================ #include #include #include #define LEN 20 #define MAXTITL 40 #define MAXAUTH 40 #define MAXBKS 10 int count = 0; //外部变量,书的数目 struct book { char title[MAXTITL]; char author[MAXAUTH]; float value; }; char * s_gets(char * st, int n); //输入字符串的函数 char get_choice(void); //获取用户选择 void add(struct book *); //添加若干本书 void change(struct book *); //替换一本书 void del(struct book *); //删除一本书 void print(struct book *); //打印书单 void write_file(struct book *, char *); //将数据写入文件 int main(void) { char name[LEN]; struct book library[MAXBKS]; char ch; FILE * fp; //打开文件并读取其中内容到结构体 printf("Please input the file name: "); s_gets(name, LEN); if ((fp = fopen(name, "a+b")) == NULL) { fprintf(stderr, "Can't open %s", name); exit(EXIT_FAILURE); } rewind(fp); while (count < MAXBKS && fread(&library[count], sizeof(struct book), 1, fp) == 1) { count++; //当前文件数 } fclose(fp); //打印文件中已有数据 printf("There are %d books:\n", count); print(library); //让用户输入选项 while ((ch = get_choice()) != 'q') { switch (ch) { case 'a': add(library); break; case 'c': change(library); break; case 'd': del(library); break; case 'p': print(library); break; default: printf("Program error.\n"); break; } } //将数据输出至文件中 write_file(library, name); return 0; } char get_choice(void) { char ch; printf("Please input your choice:\n"); printf("a. add some books c. change a book\n"); printf("d. delete a book p. print all books\n"); printf("q. quit.\n"); while ((ch = getchar()) != 'a' && ch != 'c' && ch != 'd' && ch != 'p' && ch != 'q') { while (getchar() != '\n') continue; printf("Please input the right character.\n"); } while (getchar() != '\n') continue; return ch; } void add(struct book * ps) { if (count == MAXBKS) printf("Sorry, the list is full.\n"); else { printf("Please input the title (empty line to quit):\n"); while (count < MAXBKS && s_gets(ps[count].title, MAXTITL) != NULL && ps[count].title[0] != '\0') { printf("Input the author:\n"); s_gets(ps[count].author, MAXAUTH); printf("Input the value:\n"); scanf("%f", &ps[count].value); getchar(); printf("Now, next title (empty line to quit):\n"); count++; } } } void change(struct book * ps) { int i; char name[MAXTITL]; if (count == 0) printf("Sorry, the list is empty.\n"); else { printf("Please input the title of book you want to change:\n"); s_gets(name, MAXTITL); for (i = 0; i < count; i++) { if (!strcmp(name, ps[i].title)) { printf("Please input the title of new book:\n"); s_gets(ps[i].title, MAXTITL); printf("Input the author:\n"); s_gets(ps[i].author, MAXAUTH); printf("Input the value:\n"); scanf("%f", &ps[i].value); getchar(); break; } } if (i == count) printf("Sorry, we can't find the book you input.\n"); } } void del(struct book * ps) { char name[MAXTITL]; int i, j; if (count == 0) printf("Sorry, the list is empty.\n"); printf("Please input the title of book you want to delete:\n"); s_gets(name, MAXTITL); for (i = 0; i < count; i++) { if (!strcmp(name, ps[i].title)) { for (j = i + 1; j < count; j++) ps[j - 1] = ps[j]; count--; strcpy(ps[count].title, ""); strcpy(ps[count].author, ""); ps[count].value = 0; break; } } if (i == count) printf("Sorry, we can't find the book you input.\n"); } void print(struct book * ps) { int i; for (i = 0; i < count; i++) { printf("%s by %s: $%g\n", ps[i].title, ps[i].author, ps[i].value); } } void write_file(struct book * ps, char * st) { FILE * fp; fp = fopen(st, "w+b"); fwrite(ps, sizeof(struct book), count, fp); fclose(fp); } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_14/8.c ================================================ #include #include #include #define LEN 20 #define LEN 20 #define MAX 12 struct seat { int num; int isassign; char fname[LEN]; char lname[LEN]; }; void read_file(struct seat * ps); //从文件读取 void initialize(struct seat * ps); //初始化结构 char get_choice(void); //用户输入选择 void show_number(struct seat * ps); //空位置的个数 void show_empty(struct seat * ps); //打印所有空位置 void show_list(struct seat * ps); //打印所有位置信息 void assign_seat(struct seat * ps); //预订一个位置 void delete_seat(struct seat * ps); //删除一个位置 void write_file(struct seat * ps); //数据写入文件 char * s_gets(char * st, int n); //输入字符串 int main(void) { char ch; struct seat customer[MAX]; initialize(customer); read_file(customer); //用户输入选项 while ((ch = get_choice()) != 'f') { switch (ch) { case 'a': show_number(customer); break; case 'b': show_empty(customer); break; case 'c': show_list(customer); break; case 'd': assign_seat(customer); break; case 'e': delete_seat(customer); break; default: printf("Program error.\n"); break; } } //将数据输出至文件中 write_file(customer); } void initialize(struct seat * ps) { int i; for (i = 0; i < MAX; i++) { ps[i].num = i + 1; ps[i].isassign = 0; strcpy(ps[i].fname, ""); strcpy(ps[i].lname, ""); } } void read_file(struct seat * ps) { FILE * fp; if((fp = fopen("seat.txt", "a+b")) == NULL) { fprintf(stderr, "Can't open seat.txt.\n"); exit(EXIT_FAILURE); } fread(ps, sizeof(struct seat), MAX, fp); } char get_choice(void) { char ch; printf("To choose a function, enter its letter label:\n"); printf("a) Show number of empty seats\n"); printf("b) Show list of empty seats\n"); printf("c) Show alphabetical list of seats\n"); printf("d) Assign a customer to a seat assignment\n"); printf("e) Delete a seat assignment\n"); printf("f) Quit\n"); while ((ch = getchar()) < 'a' || ch > 'f') { while (getchar() != '\n') continue; printf("Please input the right letter.\n"); } while (getchar() != '\n') continue; return ch; } void show_number(struct seat * ps) { int i; int count = 0; for(i = 0; i < MAX; i++) { if (ps[i].isassign == 0) count++; } printf("The number of empty seats is %d\n", count); } void show_empty(struct seat * ps) { int i; printf("The list of empty seats:\n"); for (i = 0; i < MAX; i++) { if (!ps[i].isassign) printf("%d ", ps[i].num); } printf("\n"); } void show_list(struct seat * ps) { int i; printf("The list of seats:\n"); for (i = 0; i < MAX; i++) { printf("%d %s %s\n", ps[i].num, ps[i].fname, ps[i].lname); } } void assign_seat(struct seat * ps) { int number; int ret_val; printf("Please input the number of seat you want to book (1 to 12):\n"); while ((ret_val = scanf("%d", &number)) != 1|| number < 1 || number > 12 || ps[number - 1].isassign == 1) { if (ret_val != 1 || number < 1 || number > 12) printf("Sorry, please input a integer from 1 to 12.\n"); else printf("Sorry, the seat is assigned, please reselect:\n"); while (getchar() != '\n') continue; } while (getchar() != '\n') continue; printf("Now, input your firstname:\n"); s_gets(ps[number - 1].fname, LEN); printf("Input your lastname:\n"); s_gets(ps[number - 1].lname, LEN); ps[number - 1].isassign = 1; printf("OK.\n"); } void delete_seat(struct seat * ps) { int number; printf("Please input the number of seat you want to delete (1 to 12):\n"); while (scanf("%d", &number) != 1 || number < 1 || number > 12 || ps[number - 1].isassign == 0) { if (ps[number - 1].isassign == 1) printf("Sorry, the seat is empty, please reselect:\n"); else printf("Sorry, please input a integer from 1 to 12.\n"); while (getchar() != '\n') continue; } getchar(); strcpy(ps[number - 1].fname, ""); strcpy(ps[number - 1].lname, ""); ps[number - 1].isassign = 0; printf("OK.\n"); } void write_file(struct seat * ps) { FILE * fp; fp = fopen("seat.txt", "w+b"); fwrite(ps, sizeof(struct seat), MAX, fp); fclose(fp); } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_14/9.c ================================================ #include #include #include #define LEN 20 #define LEN 20 #define MAX 12 #define MAXFL 5 struct seat { int num; int isassign; char fname[LEN]; char lname[LEN]; }; void read_file(struct seat * ps); //从文件读取 void initialize(struct seat * ps); //初始化结构 char get_flight(void); //用户选择航班 char get_choice(void); //用户输入选择 void show_number(struct seat * ps); //空位置的个数 void show_empty(struct seat * ps); //打印所有空位置 void show_list(struct seat * ps); //打印所有位置信息 void assign_seat(struct seat * ps); //预订一个位置 void delete_seat(struct seat * ps); //删除一个位置 void write_file(struct seat * ps); //数据写入文件 char * s_gets(char * st, int n); //输入字符串 void is_confirmed(void); //确认座位分配 //全局变量,值为1时表示被确认,值为0时未确认 int isconf; char flight_num[MAXFL]; int main(void) { char ch, flight; struct seat customer[MAX]; initialize(customer); read_file(customer); //用户输入选项 while ((flight = get_flight()) != 'q') { isconf = 0; while ((ch = get_choice()) != 'g') { switch (ch) { case 'a': show_number(customer); break; case 'b': show_empty(customer); break; case 'c': show_list(customer); break; case 'd': assign_seat(customer); break; case 'e': delete_seat(customer); break; case 'f': is_confirmed(); break; default: printf("Program error.\n"); break; } } //将数据输出至文件中 if (isconf) write_file(customer); } return 0; } void initialize(struct seat * ps) { int i; for (i = 0; i < MAX; i++) { ps[i].num = i + 1; ps[i].isassign = 0; strcpy(ps[i].fname, ""); strcpy(ps[i].lname, ""); } } void read_file(struct seat * ps) { FILE * fp; if((fp = fopen("seat.txt", "a+b")) == NULL) { fprintf(stderr, "Can't open seat.txt.\n"); exit(EXIT_FAILURE); } fread(ps, sizeof(struct seat), MAX, fp); } char get_flight(void) { char ch; printf("To choose a flight, enter its letter labal:\n"); printf("a). 102 b). 311\n"); printf("c). 444 d). 519\n"); printf("q). quit.\n"); while ((ch = getchar()) < 'a' || ch > 'd' && ch != 'q') { while (getchar() != '\n') continue; printf("Please input the right letter (a, b, c, d or q).\n"); } while (getchar() != '\n') continue; if (ch == 'a') strcpy(flight_num, "102"); else if (ch == 'b') strcpy(flight_num, "311"); else if (ch == 'c') strcpy(flight_num, "444"); else if (ch == 'd') strcpy(flight_num, "519"); return ch; } char get_choice(void) { char ch; printf("The number of the flight is %s. To choose a function, " "enter its letter label:\n", flight_num); printf("a) Show number of empty seats\n"); printf("b) Show list of empty seats\n"); printf("c) Show alphabetical list of seats\n"); printf("d) Assign a customer to a seat assignment\n"); printf("e) Delete a seat assignment\n"); printf("f) Confirmed the seat assignment\n"); printf("g) Quit\n"); while ((ch = getchar()) < 'a' || ch > 'g') { while (getchar() != '\n') continue; printf("Please input the right letter.\n"); } while (getchar() != '\n') continue; return ch; } void show_number(struct seat * ps) { int i; int count = 0; for(i = 0; i < MAX; i++) { if (ps[i].isassign == 0) count++; } printf("The number of empty seats is %d\n", count); } void show_empty(struct seat * ps) { int i; printf("The list of empty seats in %s flight:\n", flight_num); for (i = 0; i < MAX; i++) { if (!ps[i].isassign) printf("%d ", ps[i].num); } printf("\n"); } void show_list(struct seat * ps) { int i; printf("The list of seats in %s flight:\n", flight_num); for (i = 0; i < MAX; i++) { printf("%d %s %s\n", ps[i].num, ps[i].fname, ps[i].lname); } printf("The seat assignment is not confirmed.\n"); } void assign_seat(struct seat * ps) { int number; int ret_val; printf("Please input the number of seat you want to book (1 to 12) " "in %s flight:\n", flight_num); while ((ret_val = scanf("%d", &number)) != 1|| number < 1 || number > 12 || ps[number - 1].isassign == 1) { if (ret_val != 1 || number < 1 || number > 12) printf("Sorry, please input a integer from 1 to 12.\n"); else printf("Sorry, the seat is assigned, please reselect:\n"); while (getchar() != '\n') continue; } while (getchar() != '\n') continue; printf("Now, input your firstname:\n"); s_gets(ps[number - 1].fname, LEN); printf("Input your lastname:\n"); s_gets(ps[number - 1].lname, LEN); ps[number - 1].isassign = 1; printf("OK.\n"); } void delete_seat(struct seat * ps) { int number; printf("Please input the number of seat you want to delete (1 to 12) " "in %s flight:\n", flight_num); while (scanf("%d", &number) != 1 || number < 1 || number > 12 || ps[number - 1].isassign == 0) { if (ps[number - 1].isassign == 1) printf("Sorry, the seat is empty, please reselect:\n"); else printf("Sorry, please input a integer from 1 to 12.\n"); while (getchar() != '\n') continue; } getchar(); strcpy(ps[number - 1].fname, ""); strcpy(ps[number - 1].lname, ""); ps[number - 1].isassign = 0; printf("OK.\n"); } void is_confirmed(void) { isconf = 1; printf("The seat assignment is confirmed.\n"); } void write_file(struct seat * ps) { FILE * fp; fp = fopen("seat.txt", "w+b"); fwrite(ps, sizeof(struct seat), MAX, fp); fclose(fp); } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_15/1.c ================================================ #include #include int btoi(char * st); int main(void) { char * pbin = "01001001"; printf("The decimal number: %d.\n", btoi(pbin)); return 0; } int btoi(char * st) { int num = 0; while (*st) num = (num << 1) + (*st++ - '0'); return num; } ================================================ FILE: Chapter_15/2.c ================================================ #include #include #include #define SIZE 5 int btoi(char * st); //二进制字符串转化为整数的函数 char * itob(char * st, int n); //整数转化为二进制字符串的函数 void show_bstr(const char * st); //4位一组显示二进制字符串 int main(int argc, char * argv[]) { int num1, num2; char bin_st[CHAR_BIT * sizeof(int) + 1]; if (argc != 3) { fprintf(stderr, "The number of arguments is wrong.\n"); exit(EXIT_FAILURE); } num1 = btoi(argv[1]); num2 = btoi(argv[2]); show_bstr(itob(bin_st, ~num1)); show_bstr(itob(bin_st, ~num2)); show_bstr(itob(bin_st, num1 & num2)); show_bstr(itob(bin_st, num1 | num2)); show_bstr(itob(bin_st, num1 ^ num2)); return 0; } int btoi(char * st) { int num = 0; while (*st) num = (num << 1) + (*st++ - '0'); return num; } char * itob(char * st, int n) { int i; const static int size = CHAR_BIT * sizeof(int); for (i = size - 1; i >= 0; i--, n >>= 1) st[i] = (01 & n) + '0'; st[size] = '\0'; return st; } void show_bstr(const char * st) { int i = 0; while (st[i]) { putchar(st[i]); if (++i % 4 == 0 && st[i]) putchar(' '); } printf("\n"); } ================================================ FILE: Chapter_15/3.c ================================================ #include #include #define MASK 01 int count_bit_on(int num); int main(void) { int num; printf("Please input a integer:\n"); scanf("%d", &num); printf("The number of bit on is: %d\n", count_bit_on(num)); return 0; } int count_bit_on(int num) { int i; int count = 0; int size = CHAR_BIT * sizeof(int); for (i = 0; i < size; i++) { if (num & MASK) { count++; } num >>= 1; } return count; } ================================================ FILE: Chapter_15/4.c ================================================ #include #define MASK 01 int check_bit(int num, int bit); int main(void) { int num, bit; printf("Please input a integer:\n"); scanf("%d", &num); printf("Now input the position:\n"); scanf("%d", &bit); printf("The number in your position is: %d.\n", check_bit(num, bit)); return 0; } int check_bit(int num, int bit) { int i; for (i = 0; i < bit; i++) { num >>= 1; } return num & MASK; } ================================================ FILE: Chapter_15/5.c ================================================ #include #include #define MASK 01 #define SIZE CHAR_BIT * sizeof(unsigned int) char * itob(char * st, unsigned int n); void show_bstr(const char * st); unsigned int move_left(unsigned int, int); int main(void) { unsigned int num; int bit; char st[SIZE + 1]; printf("Please input a integer and the number of bits to move:\n"); scanf("%u%d", &num, &bit); printf("The original binary string:\n"); show_bstr(itob(st, num)); //把所有位向左移动 num = move_left(num, bit); printf("The present binary string:\n"); show_bstr(itob(st, num)); } unsigned int move_left(unsigned int n, int bit) { int i; for (i = 0; i < bit; i++) { n = (n << 1) + ((n >> (SIZE - 1)) & MASK); } return n; } char * itob(char * st, unsigned int n) { int i; for (i = SIZE - 1; i >= 0; i--, n >>= 1) st[i] = (01 & n) + '0'; st[SIZE] = '\0'; return st; } void show_bstr(const char * st) { int i = 0; while (st[i]) { putchar(st[i]); if (++i % 4 == 0 && st[i]) putchar(' '); } printf("\n"); } ================================================ FILE: Chapter_15/6.c ================================================ #include #include struct word { unsigned int font: 8; unsigned int size: 7; unsigned int alignment: 2; unsigned int bold: 1; unsigned int italic: 1; }; const char * align[3] = {"left", "center", "right"}; const char * open[2] = {"off", "on"}; char get_choice(void); char get_select(void); void print(struct word *); int main(void) { struct word type = {1, 12, 0, 0, 0}; char choice; char ch; int num; print(&type); while ((choice = get_choice()) != 'q') { switch (choice) { case 'f': printf("Enter font ID (0 - 256): "); scanf("%u", &num); getchar(); type.font = num; break; case 's': printf("Enter font ID (0 - 127): "); scanf("%u", &num); getchar(); type.size = num; break; case 'a': printf("Select alignment:\n"); printf("l)left c)center r)right\n"); if ((ch = get_select()) == 'l') type.alignment = 0; else if (ch == 'c') type.alignment = 1; else type.alignment = 2; break; case 'b': type.bold = !type.bold; break; case 'i': type.italic = !type.italic; break; default : break; } print(&type); } printf("Bye.\n"); return 0; } char get_choice(void) { char ch; printf("f)change font\ts)change size\ta)change alignment\n"); printf("b)toggle bold\ti)toggle italic\nq)quit\n"); while (strchr("fsabiq", ch = getchar()) == NULL) { while (getchar() != '\n') continue; printf("Please input the right letter.\n"); } while (getchar() != '\n') continue; return ch; } char get_select(void) { char ch; while (strchr("lcr", ch = getchar()) == NULL) { while (getchar() != '\n') continue; printf("Please input the right letter.\n"); } while (getchar() != '\n') continue; return ch; } void print(struct word * pst) { printf("\n ID SIZE ALIGNMENT B I\n"); printf("%3u", pst->font); printf("%5u", pst->size); printf("%10s", align[pst->alignment]); printf("%7s", open[pst->bold]); printf("%5s\n\n", open[pst->italic]); } ================================================ FILE: Chapter_15/7.c ================================================ #include #include #define ID_MASK 0xff //括号缺失会出错 #define SIZE_MASK (0x7f << 8) #define ALIGN_MASK (0x3 << 15) #define CENTER (0x1 << 15) #define RIGHT (0x2 << 15) #define BOLD (0x1 << 17) #define ITALIC (0x1 << 18) const char * align[3] = {"left", "center", "right"}; const char * open[2] = {"off", "on"}; char get_choice(void); char get_select(void); void print(unsigned long); int main(void) { unsigned long type = 0; char choice; char ch; int num; print(type); while ((choice = get_choice()) != 'q') { switch (choice) { case 'f': printf("Enter font ID (0 - 256): "); scanf("%lu", &num); getchar(); type &= ~ID_MASK; //把表示字体ID的位清空 type |= num; //重置字体ID break; case 's': printf("Enter font ID (0 - 127): "); scanf("%lu", &num); getchar(); type &= ~SIZE_MASK; type |= (num << 8); break; case 'a': type &= ~ALIGN_MASK; printf("Select alignment:\n"); printf("l)left c)center r)right\n"); if ((ch = get_select()) == 'c') type |= CENTER; else if (ch == 'r') type |= RIGHT; break; case 'b': type ^= BOLD; break; case 'i': type ^= ITALIC; break; default : break; } print(type); } printf("Bye.\n"); return 0; } char get_choice(void) { char ch; printf("f)change font\ts)change size\ta)change alignment\n"); printf("b)toggle bold\ti)toggle italic\nq)quit\n"); while (strchr("fsabiq", ch = getchar()) == NULL) { while (getchar() != '\n') continue; printf("Please input the right letter.\n"); } while (getchar() != '\n') continue; return ch; } char get_select(void) { char ch; while (strchr("lcr", ch = getchar()) == NULL) { while (getchar() != '\n') continue; printf("Please input the right letter.\n"); } while (getchar() != '\n') continue; return ch; } void print(unsigned long num) { printf("\n ID SIZE ALIGNMENT B I\n"); printf("%3u", num & ID_MASK); printf("%5u", (num & SIZE_MASK) >> 8); printf("%10s", align[(num & ALIGN_MASK) >> 15]); printf("%7s", open[(num & BOLD) >> 17]); printf("%5s\n\n", open[(num & ITALIC) >> 18]); } ================================================ FILE: Chapter_16/2.c ================================================ #include #define HORMONIC(x, y) (1 / (1 / (x) + 1 / (y))) int main(void) { double num1, num2; printf("Please input two number ('q' to quit): "); while (scanf("%lf%lf", &num1, &num2) == 2) { printf("The hormonic average: %.2f\n", HORMONIC(num1, num2)); printf("Please input two number ('q' to quit): "); } return 0; } ================================================ FILE: Chapter_16/3.c ================================================ #include #include #define DEG_TO_RED ((4 * atan(1)) / 180) typedef struct polar_v { double magnitude; double angle; } Polar_V; typedef struct rect_v { double x; double y; } Rect_V; Rect_V polar_to_rect(Polar_V pv); int main(void) { Polar_V input; Rect_V result; puts("Enter magnitude and angle; enter q to quit:"); while (scanf("%lf%lf", &input.magnitude, &input.angle) == 2) { result = polar_to_rect(input); printf("x = %.2f, y = %.2f\n", result.x, result.y); puts("Next input (q to quit):"); } puts("Bye."); return 0; } Rect_V polar_to_rect(Polar_V pv) { Rect_V rv; rv.x = pv.magnitude * cos(pv.angle * DEG_TO_RED); rv.y = pv.magnitude * sin(pv.angle * DEG_TO_RED); return rv; } ================================================ FILE: Chapter_16/4.c ================================================ #include #include void delay(double time); int main(void) { double time; printf("Please input the time (in seconds) to delay" " (q to quit):\n"); while (scanf("%lf", &time) == 1) { delay(time); printf("Time is out.\n"); printf("Your next input (q to quit):\n"); } return 0; } void delay(double time) { double t; t = (double) clock() / CLOCKS_PER_SEC; while ((double) clock() / CLOCKS_PER_SEC - t < time) ; } ================================================ FILE: Chapter_16/5.c ================================================ #include #include #include #include #define SIZE 10 void random(const int ar[], int size, int n); int main(void) { int ar[SIZE] = {1, 2, 3, 6, 7, 9, 10, 13, 26, 17}; int i; int num; srand((unsigned int) time(NULL)); printf("The original array:\n"); for (i = 0; i < SIZE; i++) printf("%d ", ar[i]); printf("\nPlease input the number of integers (no more than 10)\n"); printf("you want to take (q to quit):\n"); while (scanf("%d", &num) == 1) { random(ar, SIZE, num); printf("Your next input (q to quit):\n"); } puts("Bye."); return 0; } void random(const int ar[], int size, int n) { int i; int count; int index; int acpy[SIZE]; //创建一个数组副本,避免修改原始数组 memcpy(acpy, ar, SIZE * sizeof(int)); if (n > size) printf("The number is too big.\n"); else { for (count = 0; count < n; count++) { index = rand() % size; printf("%d ", acpy[index]); for (i = index; i < size - 1; i++) { acpy[i] = acpy[i + 1]; } size--; } printf("\n"); } } ================================================ FILE: Chapter_16/6.c ================================================ #include #include #include #define SIZE 40 #define NUM 5 struct names { char first[SIZE]; char last[SIZE]; }; int comp(const void * p1, const void * p2); int main(void) { int i; struct names staff[NUM] = { {"zha", "yujie"}, {"xia", "yufeng"}, {"bu", "jianqiang"}, {"xu", "feifan"}, {"ding","bing"} }; qsort(staff, NUM, sizeof(struct names), comp); for (i = 0; i < NUM; i++) { printf("%s %s\n", staff[i].first, staff[i].last); } return 0; } int comp(const void * p1, const void * p2) { const struct names *ps1 = (const struct names *) p1; const struct names *ps2 = (const struct names *) p2; int res; res = strcmp(ps1->first, ps2->first); if (res) return res; else return strcmp(ps1->last, ps2->last); } ================================================ FILE: Chapter_16/7.c ================================================ #include #include #include #define SIZE 40 void show_array(const double ar[], int n); double * new_d_array(int n, ...); int main() { double * p1; double * p2; p1 = new_d_array(5, 1.2, 2.3, 3.4, 4.5, 5.6); p2 = new_d_array(4, 100.0, 20.00, 8.08, -1890.0); show_array(p1, 5); show_array(p2, 4); free(p1); free(p2); return 0; } void show_array(const double ar[], int n) { int i; for (i = 0; i < n; i++) printf("%g ", ar[i]); printf("\n"); } double * new_d_array(int n, ...) { int i; double * p = (double *) malloc(n * sizeof(double)); va_list ap; va_start(ap, n); for (i = 0; i < n; i++) *(p + i) = va_arg(ap, double); va_end(ap); return p; } ================================================ FILE: Chapter_17/1.c ================================================ #include #include #include #define TSIZE 45 typedef struct film { char title[TSIZE]; int rating; struct film * prev; struct film * next; } Node; char * s_gets(char * st, int n); int main(void) { Node * head = NULL; Node * pre = NULL; Node * end; Node * current; char input[TSIZE]; //储存信息 puts("Enter first movie title:"); while (s_gets(input, TSIZE) != NULL && input[0] != '\0') { current = (Node *) malloc(sizeof(Node)); if (head == NULL) head = current; else { pre->next = current; } current->prev = pre; current->next = NULL; strcpy(current->title, input); puts("Enter your rating <0-10>:"); scanf("%d", ¤t->rating); while (getchar() != '\n') continue; puts("Enter next movie title (empty to stop):"); pre = current; } end = pre; if (head == NULL) { fprintf(stderr, "No data entered.\n"); exit(1); } else printf("Here is the movie list in positive order:\n"); //正序显示电影列表 current = head; while (current != NULL) { printf("Movie: %s Rating: %d\n", current->title, current->rating); current = current->next; } //逆序显示电影列表 printf("Here is the movie list in reverse order:\n"); current = end; while (current != NULL) { printf("Movie: %s Rating: %d\n", current->title, current->rating); current = current->prev; } return 0; } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while(getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_17/2movie/2.c ================================================ #include #include #include #include "movie.h" void show_list(Item item); char * s_gets(char * st, int n); int main(void) { List movies; Item temp; //初始化 InitializeList(&movies); if (ListIsFull(&movies)) { fprintf(stderr, "No memory available.\n"); exit(1); } //储存数据 printf("Please input the title of movie:\n"); while (s_gets(temp.titile, TSIZE) != NULL && temp.titile[0] != '\0') { printf("Enter your rating <0-10>:\n"); scanf("%d", &temp.rating); while (getchar() != '\n') continue; if (AddItem(&movies, temp) == 0) { fprintf(stderr, "Allocting memory error.\n"); break; } if (ListIsFull(&movies)) { fprintf(stderr, "Sorry, the list is full.\n"); break; } printf("Input the next title (Empty line to stop):\n"); } //显示数据 if (ListIsEmpty(&movies)) { fprintf(stderr, "Sorry, the list is empty.\n"); return 0; } printf("Here is the movie list:\n"); Traverse(&movies, show_list); printf("You entered %u movies.\n", ListItemCount(&movies)); //清空数据 DeleteAll(&movies); printf("Bye.\n"); return 0; } void show_list(Item item) { printf("Movie: %s Rating: %d\n", item.titile, item.rating); } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if(ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_17/2movie/movie.c ================================================ #include #include #include "movie.h" //初始化链表为空 void InitializeList(List * plist) { plist->head = NULL; plist->end = NULL; } //链表为空,返回1 int ListIsEmpty(const List * plist) { if (plist->head == NULL) return 1; else return 0; } //链表为满,返回1 int ListIsFull(const List * plist) { Node * pt; int full; pt = (Node *)malloc(sizeof(Node)); if (pt == NULL) full = 1; else full = 0; free(pt); return full; } //为链表添加项,成功返回1 int AddItem(List * plist, Item item) { Node * pnew; pnew = (Node *)malloc(sizeof(Node)); if (pnew == NULL) return 0; pnew->next = NULL; pnew->item = item; if (plist->head == NULL) plist->head = pnew; else plist->end->next = pnew; plist->end = pnew; return 1; } //确定链表的项数 unsigned int ListItemCount(List * plist) { unsigned int count = 0; Node * pnode = plist->head; while (pnode != NULL) { pnode = pnode->next; count++; } return count; } //遍历链表 void Traverse(const List * plist, void (*pfun)(Item item)) { Node * pnode = plist->head; while (pnode != NULL) { (*pfun)(pnode->item); pnode = pnode->next; } } //清空链表 void DeleteAll(List * plist) { Node * pnode; while (plist->head != NULL) { pnode = plist->head; plist->head = plist->head->next; free(pnode); } } ================================================ FILE: Chapter_17/2movie/movie.h ================================================ #ifndef MOVIE_H_ #define MOVIE_H_ #define TSIZE 45 typedef struct film { char titile[TSIZE]; int rating; } Item; typedef struct node { Item item; struct node * next; } Node; typedef struct list { Node * head; Node * end; } List; //初始化链表为空 void InitializeList(List * plist); //链表为空,返回1 int ListIsEmpty(const List * plist); //链表为满,返回1 int ListIsFull(const List * plist); //为链表添加项,成功返回1 int AddItem(List * plist, Item item); //确定链表的项数 unsigned int ListItemCount(List * plist); //遍历链表 void Traverse(const List * plist, void (*pfun)(Item item)); //清空链表 void DeleteAll(List * plist); #endif ================================================ FILE: Chapter_17/3movie/3.c ================================================ #include #include #include #include "movie2.h" void show_list(Item item); char * s_gets(char * st, int n); int main(void) { List movies; Item temp; //初始化 InitializeList(&movies); if (ListIsFull(&movies)) { fprintf(stderr, "No memory available.\n"); exit(1); } //储存数据 printf("Please input the title of movie:\n"); while (s_gets(temp.titile, TSIZE) != NULL && temp.titile[0] != '\0') { printf("Enter your rating <0-10>:\n"); scanf("%d", &temp.rating); while (getchar() != '\n') continue; if (AddItem(&movies, temp) == 0) { fprintf(stderr, "Allocting memory error.\n"); break; } if (ListIsFull(&movies)) { fprintf(stderr, "Sorry, the list is full.\n"); break; } printf("Input the next title (Empty line to stop):\n"); } //显示数据 if (ListIsEmpty(&movies)) { fprintf(stderr, "Sorry, the list is empty.\n"); return 0; } printf("Here is the movie list:\n"); Traverse(&movies, show_list); printf("You entered %u movies.\n", ListItemCount(&movies)); //清空数据 DeleteAll(&movies); printf("Bye.\n"); return 0; } void show_list(Item item) { printf("Movie: %s Rating: %d\n", item.titile, item.rating); } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if(ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_17/3movie/movie2.c ================================================ #include #include #include #include "movie2.h" //初始化链表为空 void InitializeList(List * plist) { int i; for (i = 0; i < MAXSIZE; i++) { strcpy((plist->entries[i]).titile, ""); (plist->entries[i]).rating = 0; plist->items = 0; } } //链表为空,返回1 int ListIsEmpty(const List * plist) { if (plist->items == 0) return 1; else return 0; } //链表为满,返回1 int ListIsFull(const List * plist) { if (plist->items == MAXSIZE) return 1; else return 0; } //为链表添加项,成功返回1 int AddItem(List * plist, Item item) { if (plist->items == MAXSIZE) { fprintf(stderr, "The list is full.\n"); return 0; } plist->entries[plist->items] = item; (plist->items)++; return 1; } //确定链表的项数 unsigned int ListItemCount(List * plist) { return plist->items; } //遍历链表 void Traverse(const List * plist, void (*pfun)(Item item)) { int i; for (i = 0; i < plist->items; i++) { (*pfun)(plist->entries[i]); } } //清空链表 void DeleteAll(List * plist) { int i; for (i = 0; i < plist->items; i++) { strcpy((plist->entries[i]).titile, ""); (plist->entries[i]).rating = 0; plist->items = 0; } } ================================================ FILE: Chapter_17/3movie/movie2.h ================================================ #ifndef MOVIE_H_ #define MOVIE_H_ #define TSIZE 45 #define MAXSIZE 5 typedef struct film { char titile[TSIZE]; int rating; } Item; typedef struct list { Item entries[MAXSIZE]; int items; } List; //ʼΪ void InitializeList(List * plist); //Ϊ,1 int ListIsEmpty(const List * plist); //Ϊ1 int ListIsFull(const List * plist); //Ϊɹ1 int AddItem(List * plist, Item item); //ȷ unsigned int ListItemCount(List * plist); // void Traverse(const List * plist, void (*pfun)(Item item)); // void DeleteAll(List * plist); #endif ================================================ FILE: Chapter_17/4queue/mall.c ================================================ #include #include #include #include "queue.h" #define MIN_PER_HOUR 60 int newcustomer(double x); Item customertime(long when); Queue line1; Queue line2; Item temp; int hours; //模拟的小时数 int cust_per_hour; //平均每小时来的顾客数 int wait_time1 = 0; //摊位1从当前到空闲的时间 int wait_time2 = 0; //摊位2从当前到空闲的时间 long cycle; //循环次数 long cyclelimit; //循环的最大数 long turnaways = 0; //被拒的顾客数 long customers = 0; //加入队列的顾客数 long served = 0; //接受服务的顾客数 long sum_line = 0; //累计队列总长 long line_wait = 0; //累计队列等候时间 double min_per_cust; //顾客到来的平均间隔时间 int main(void) { printf("Enter the number of simulation hours:\n"); scanf("%d", &hours); printf("Enter the average number of customers per hour:\n"); scanf("%d", &cust_per_hour); cyclelimit = MIN_PER_HOUR * hours; min_per_cust = MIN_PER_HOUR / cust_per_hour; InitializeQueue(&line1); InitializeQueue(&line2); srand((unsigned int) time(0)); for (cycle = 0; cycle < cyclelimit; cycle++) { if (newcustomer(min_per_cust)) //如果一分钟内有顾客来 { if (QueueIsFull(&line1) && QueueIsFull(&line2)) turnaways++; else { customers++; temp = customertime(cycle); if (line1.items > line2.items) EnQueue(&line2, temp); else if (line1.items < line2.items) EnQueue(&line1, temp); else (rand() % 2) ? EnQueue(&line1, temp) : EnQueue(&line2, temp); } } if (wait_time1 <= 0 && !QueueIsEmpty(&line1)) { DeQueue(&line1, &temp); wait_time1 = temp.processtime; line_wait += cycle - temp.arrive; served++; } if (wait_time2 <= 0 && !QueueIsEmpty(&line2)) { DeQueue(&line2, &temp); wait_time2 = temp.processtime; line_wait += cycle - temp.arrive; served++; } if (wait_time1 > 0) wait_time1--; if (wait_time2 > 0) wait_time2--; sum_line += (long) QueueItemCount(&line1) + (long) QueueItemCount(&line2); } if (customers > 0) { printf("customers accepted: %ld\n", customers); printf(" customers served: %ld\n", served); printf(" turnaways: %ld\n", turnaways); printf("average queue size: %.2f\n", (double) sum_line / cyclelimit); printf(" average wait time: %.2f minutes\n", (double) line_wait / served); } else puts("No customers!"); DeleteAll(&line1); DeleteAll(&line2); puts("Bye!"); return 0; } //一分钟之内有顾客来,返回1 int newcustomer(double x) { if (x * rand() / RAND_MAX < 1) return 1; else return 0; } Item customertime(long when) { Item cust; cust.arrive = when; cust.processtime = rand() % 3 + 1; return cust; } ================================================ FILE: Chapter_17/4queue/queue.c ================================================ #include #include #include "queue.h" static void AddItem(Node * pq, Item item); static void CopyItem(Node * pnode, Item * pitem); //接口函数 //初始化队列 void InitializeQueue(Queue * pq) { pq->head = NULL; pq->end = NULL; pq->items = 0; } //确定队列为空 int QueueIsEmpty(const Queue * pq) { if (pq->items == 0) return 1; else return 0; } //确定队列为满 int QueueIsFull(const Queue * pq) { if (pq->items == MAXSIZE) return 1; else return 0; } //确定队列项数 unsigned int QueueItemCount(const Queue * pq) { return pq->items; } //给队列末尾添加项 int EnQueue(Queue * pq, Item item) { Node * pnode; if (QueueIsFull(pq)) { fprintf(stderr, "The queue is full.\n"); return 0; } pnode = (Node *) malloc(sizeof(Node)); if (pnode == NULL) { fprintf(stderr, "Can't alloc memory.\n"); return 0; } AddItem(pnode, item); pnode->next = NULL; pq->items++; if (pq->head == NULL) { pq->head = pnode; } else pq->end->next = pnode; pq->end = pnode; return 1; } //从队列开头删除项 int DeQueue(Queue * pq, Item * pitem) { Node * pnode; if (QueueIsEmpty(pq)) { fprintf(stderr, "the queue is empty.\n"); return 0; } CopyItem(pq->head, pitem); pnode = pq->head; pq->head = pq->head->next; free(pnode); pq->items--; if (pq->items == 0) pq->end = NULL; return 1; } //清空队列 void DeleteAll(Queue * pq) { Item item; while (!QueueIsEmpty(pq)) DeQueue(pq, &item); } //局域函数 static void AddItem(Node * pnode, Item item) { pnode->item = item; } static void CopyItem(Node * pnode, Item * pitem) { *pitem = pnode->item; } ================================================ FILE: Chapter_17/4queue/queue.h ================================================ #ifndef QUEUE_H_ #define QUEUE_H_ #define MAXSIZE 10 typedef struct item { long arrive; int processtime; } Item; typedef struct node { Item item; struct node * next; } Node; typedef struct queue { Node * head; Node * end; int items; } Queue; //初始化队列 void InitializeQueue(Queue * pq); //确定队列为空 int QueueIsEmpty(const Queue * pq); //确定队列为满 int QueueIsFull(const Queue * pq); //确定队列项数 unsigned int QueueItemCount(const Queue * pq); //给队列末尾添加项 int EnQueue(Queue * pq, Item item); //从队列开头删除项 int DeQueue(Queue * pq, Item * pitem); //清空队列 void DeleteAll(Queue * pq); #endif ================================================ FILE: Chapter_17/5stack/5.c ================================================ #include #include #include #include "stack.h" #define SIZE 40 char * s_gets(char * st, int n); int main(void) { Stack stack; Item temp[SIZE]; Item ch; int i; InitializeStack(&stack); //将用户输入数据压入栈中 printf("Enter a string:\n"); while (s_gets(temp, SIZE) != NULL && temp[0] != '\0') { for (i = 0; temp[i] != '\0'; i++) { if (AddItem(&stack, temp[i]) == 0) { break; } } if (StackIsFull(&stack)) { fprintf(stderr, "The stack is full.\n"); break; } printf("Your next string (empty line to stop):\n"); } //从栈中弹出数据并输出 if (StackIsEmpty(&stack)) { fprintf(stderr, "There is no data.\n"); exit(1); } printf("You input %d charcters.\n", StackItemCount(&stack)); printf("The string in reverse order:\n"); while (StackIsEmpty(&stack) != 1) { DelItem(&stack, &ch); putchar(ch); } printf("\nBye.\n"); return 0; } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_17/5stack/stack.c ================================================ #include #include "stack.h" //初始化栈 void InitializeStack(Stack * ps) { ps->items = 0; } //确定栈为空 int StackIsEmpty(const Stack * ps) { return (ps->items == 0) ? 1 : 0; } //确定栈为满 int StackIsFull(const Stack * ps) { return (ps->items == SMAX) ? 1 : 0; } //统计栈内项数 int StackItemCount(const Stack * ps) { return ps->items; } //从栈顶压入项 int AddItem(Stack * ps, Item item) { if (StackIsFull(ps)) return 0; else { ps->item[ps->items] = item; ps->items++; return 1; } } //从栈顶弹出项 int DelItem(Stack * ps, Item * pitem) { if (StackIsEmpty(ps)) return 0; else { * pitem = ps->item[ps->items - 1]; ps->item[ps->items - 1] = '\0'; ps->items--; return 1; } } ================================================ FILE: Chapter_17/5stack/stack.h ================================================ #ifndef STACK_H_ #define STACK_H_ #define SMAX 100 typedef char Item; typedef struct stack { Item item[SMAX]; int items; } Stack; //初始化栈 void InitializeStack(Stack * ps); //确定栈为空 int StackIsEmpty(const Stack * ps); //确定栈为满 int StackIsFull(const Stack * ps); //统计栈内项数 int StackItemCount(const Stack * ps); //从栈顶压入项 int AddItem(Stack * ps, Item item); //从栈顶弹出项 int DelItem(Stack * ps, Item * pitem); //清空项 void EmptyItem(Stack * ps); #endif ================================================ FILE: Chapter_17/6.c ================================================ #include #define SIZE 8 int find(int ar[], int size, int n); int main(void) { int n; int array[SIZE] = {1, 3, 6, 7, 9, 10, 13, 15}; printf("Please input the integer you want to search:\n"); while (scanf("%d", &n) == 1) { if (find(array, SIZE, n)) printf("Find.\n"); else printf("Can't find.\n"); printf("Your next input (q to quit):\n"); } return 0; } int find(int * ar, int size, int n) { int head = 0; int end = size - 1; int mid; while (head <= end) { mid = (head + end) / 2; if (n < ar[mid]) end = mid - 1; else if (n > ar[mid]) head = mid + 1; else return 1; } return 0; } ================================================ FILE: Chapter_17/7word/7.c ================================================ #include #include #include #include #include "word.h" #define LEN 40 #define SIZE 40 char get_choice(void); char * s_gets(char * st, int n); void count_word(Tree * pt, Item * item); void print_word(Item temp); int main(void) { Tree words; Item temp; FILE * fp; char ch; char name[LEN]; char word[SIZE]; //打开文件 printf("Please input the file name:\n"); s_gets(name, LEN); if ((fp = fopen(name, "r")) == NULL) { fprintf(stderr, "Can't open the file.\n"); exit(1); } //从文件读取单词 InitializeTree(&words); while (fscanf(fp, "%s", word) == 1) { strcpy(temp.word, word); temp.num = 1; AddItem(&words, &temp); if (TreeIsFull(&words)) { fprintf(stderr, "The tree is full.\n"); break; } } fclose(fp); while ((ch = get_choice()) != 'q') { if (ch == 'a') { if (TreeIsEmpty(&words)) printf("There is no word.\n"); else Traverse(&words, print_word); } else count_word(&words, &temp); } DeleteAll(&words); printf("Bye.\n"); return 0; } char get_choice(void) { char ch; printf("\na. show word list\n"); printf("b. find a word\n"); printf("q. quit\n"); ch = getchar(); while (strchr("abq", tolower(ch)) == NULL) { while (getchar() != '\n') continue; printf("Please input the a, b, or q.\n"); ch = getchar(); } while (getchar() != '\n') continue; return ch; } void print_word(Item temp) { printf("word: %s\t\t\tcount: %d\n", temp.word, temp.num); } void count_word(Tree * pt, Item * item) { int count; printf("Enter the word you want to search:\n"); s_gets(item->word, SIZE); item->num = 1; count = ItemCount(pt, item); if (!count) printf("Can't find the word.\n"); else printf("count: %d\n", ItemCount(pt, item)); } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_17/7word/word.c ================================================ #include #include #include #include "word.h" //局域数据类型 typedef struct pair { Trnode * parent; Trnode * child; } Pair; //局域函数声明 static Pair SeekItem(const Tree * ptree, Item * pi); static int ToLeft(Item * p1, Item * p2); static int ToRight(Item * p1, Item * p2); static Trnode * MakeNode(Item * item); static void AddNode(Trnode * new_node, Trnode * root); static void DeleteNode(Trnode * * ptr); static void InOrder(Trnode * root, void (*pfun)(Item item)); static void DeleteAllNodes(Trnode * root); //接口函数 //初始化树 void InitializeTree(Tree * ptree) { ptree->root = NULL; ptree->size = 0; } //确认树为满 int TreeIsFull(const Tree * ptree) { if (ptree->size == MAX) return 1; else return 0; } //确认树为空 int TreeIsEmpty(const Tree * ptree) { if (ptree->size == 0) return 1; else return 0; } //统计项数 int TreeItemCount(const Tree * ptree) { return ptree->size; } //查找项 int InTree(const Tree * ptree, const Item * pi) { Pair look; look = SeekItem(ptree, pi); if (look.child != NULL) return 1; else return 0; } //添加项 int AddItem(Tree * ptree, const Item * pi) { Pair look; Trnode * new_node; if (TreeIsFull(ptree)) return 0; look = SeekItem(ptree, pi); if (look.child != NULL) { (look.child->item.num)++; return 1; } else { new_node = MakeNode(pi); if (new_node == NULL) { fprintf(stderr, "Could't eate node\n"); return 0; } ptree->size++; if (ptree->root == NULL) ptree->root = new_node; else AddNode(new_node, ptree->root); } return 1; } //删除项 int DelItem(Tree * ptree, const Item * pi) { Pair look; look = SeekItem(ptree, pi); if (look.child == NULL) return 0; if (look.parent == NULL) DeleteNode(&ptree->root); else if (look.parent->left == look.child) DeleteNode(&look.parent->left); else DeleteNode(&look.parent->right); ptree->size--; return 1; } //遍历树 void Traverse(const Tree * ptree, void (*pfun)(Item item)) { if (ptree != NULL) InOrder(ptree->root, pfun); } //清空树 void DeleteAll(Tree * ptree) { if (ptree != NULL) DeleteAllNodes(ptree->root); ptree->root = NULL; ptree->size = 0; } //每一项计数 int ItemCount(const Tree * ptree, const Item * item) { Pair look; look = SeekItem(ptree, item); if (look.child == NULL) return 0; else return look.child->item.num; } //局域函数 //寻找项 static Pair SeekItem(const Tree * ptree, const Item * pi) { Pair look; look.parent = NULL; look.child = ptree->root; if (look.child == NULL) return look; while (look.child != NULL) { if (ToLeft(pi, &(look.child->item))) { look.parent = look.child; look.child = look.child->left; } else if (ToRight(pi, &(look.child->item))) { look.parent = look.child; look.child = look.child->right; } else break; } return look; } //项在左边 static int ToLeft(Item * p1, Item * p2) { if (strcmp(p1->word, p2->word) < 0) return 1; else return 0; } //项在右边 static int ToRight(Item * p1, Item * p2) { if (strcmp(p1->word, p2->word) > 0) return 1; else return 0; } static Trnode * MakeNode(Item * item) { Trnode * pnode; pnode = (Trnode *) malloc(sizeof(Trnode)); if (pnode != NULL) { pnode->item = *item; pnode->left = NULL; pnode->right = NULL; } return pnode; } static void AddNode(Trnode * new_node, Trnode * root) { if (ToLeft(&(new_node->item), &(root->item))) { if (root->left == NULL) root->left = new_node; else AddNode(new_node, root->left); } else if (ToRight(&(new_node->item), &(root->item))) { if (root->right == NULL) root->right = new_node; else AddNode(new_node, root->right); } else { fprintf(stderr, "location error in AddNode().\n"); exit(1); } } //ptr 是父节点指向目标节点的指针的地址 static void DeleteNode(Trnode * * ptr) { Trnode * pnode; if ((*ptr)->left == NULL) { pnode = *ptr; *ptr = (*ptr)->right; free(pnode); } else if ((*ptr)->right == NULL) { pnode = *ptr; *ptr = (*ptr)->left; free(pnode); } else { for (pnode = (*ptr)->left; pnode->right != NULL; pnode = pnode->right) continue; pnode->right = (*ptr)->right; pnode = (*ptr); *ptr = (*ptr)->left; free(pnode); } } static void InOrder(Trnode * root, void (*pfun)(Item item)) { if (root != NULL) { InOrder(root->left, pfun); (*pfun)(root->item); InOrder(root->right, pfun); } } static void DeleteAllNodes(Trnode * root) { Trnode * pright; if (root != NULL) { pright = root->right; DeleteAllNodes(root->left); free(root); DeleteAllNodes(pright); } } ================================================ FILE: Chapter_17/7word/word.h ================================================ #ifndef WORD_H_ #define WORD_H_ #define LEN 40 #define MAX 100 typedef struct item { char word[LEN]; int num; } Item; typedef struct trnode { Item item; struct trnode * left; struct trnode * right; } Trnode; typedef struct tree { Trnode * root; int size; } Tree; //初始化树 void InitializeTree(Tree * ptree); //确认树为满 int TreeIsFull(const Tree * ptree); //确认树为空 int TreeIsEmpty(const Tree * ptree); //统计项数 int TreeItemCount(const Tree * ptree); //查找项 int InTree(const Tree * ptree, const Item * pi); //添加项 int AddItem(Tree * ptree, const Item * pi); //删除项 int DelItem(Tree * ptree, const Item * pi); //遍历树 void Traverse(const Tree * ptree, void (*pfun)(Item item)); //清空树 void DeleteAll(Tree * ptree); //对某一项计数 int ItemCount(const Tree * ptree, const Item * item); #endif ================================================ FILE: Chapter_17/8pet/8.c ================================================ #include #include #include #include #include "pet.h" char get_choice(void); char * s_gets(char * st, int n); void addpet(Tree * pt); void printpet(Item temp); void findpet(const Tree * pt); void droppet(Tree * pt); void showpet(const Tree * pt); int main(void) { Tree pet; char ch; InitializeTree(&pet); while ((ch = get_choice()) != 'q') { switch (ch) { case 'a': addpet(&pet); break; case 'l': showpet(&pet); break; case 'f': findpet(&pet); break; case 'n': printf("%d pets in club.\n", TreeItemCount(&pet)); break; case 'd': droppet(&pet); break; default: puts("Swithing error"); } printf("\n"); } DeleteAll(&pet); printf("Bye.\n"); return 0; } char get_choice(void) { char ch; puts("Nerfville Pet Club Membership Program"); puts("Enter the letter corresponding to your choice:"); puts("a) add a pet l) show list of pets"); puts("n) number of pets f) find pets"); puts("d) delete a pet q) quit"); ch = getchar(); while (strchr("alnfdq", tolower(ch)) == NULL) { while (getchar() != '\n') continue; printf("Please input the a, b, or q.\n"); ch = getchar(); } while (getchar() != '\n') continue; return ch; } void showpet(const Tree * pt) { if (TreeIsEmpty(pt)) printf("No pet in club.\n"); else Traverse(pt, printpet); } void findpet(const Tree * pt) { Item temp; if (TreeIsEmpty(pt)) puts("No pet in the club.\n"); else { printf("Enter the name of pet:\n"); s_gets(temp.name, LEN); FindItem(pt, &temp); } } void addpet(Tree * pt) { Item temp; if (TreeIsFull(pt)) puts("No room in the club.\n"); else { printf("Enter the name of pet:\n"); s_gets(temp.name, LEN); printf("Enter the kind of pet:\n"); s_gets(temp.kind[0], LEN); temp.num = 1; AddItem(pt, &temp); } } void droppet(Tree * pt) { Item temp; if (TreeIsEmpty(pt)) { puts("No entries.\n"); return; } printf("Enter the name of pet:\n"); s_gets(temp.name, LEN); if (DelItem(pt, &temp) == 0) { printf("Can't find the pet.\n"); } } void printpet(Item temp) { int i; printf("name: %s\t\tkind: ", temp.name); for (i = 0; i < temp.num; i++) printf("%s ", temp.kind[i]); printf("\n"); } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; } ================================================ FILE: Chapter_17/8pet/pet.c ================================================ #include #include #include #include "pet.h" //局域数据类型 typedef struct pair { Trnode * parent; Trnode * child; } Pair; //内部链接,文件作用域 static int count = 0; //局域函数声明 static Pair SeekItem(const Tree * ptree, const Item * pi); static int ToLeft(const Item * p1, const Item * p2); static int ToRight(const Item * p1, const Item * p2); static Trnode * MakeNode(const Item * item); static void AddNode(Trnode * new_node, Trnode * root); static void DeleteNode(Trnode * * ptr); static void InOrder(Trnode * root, void (*pfun)(Item item)); static void DeleteAllNodes(Trnode * root); static void CountItem(Trnode * root); //接口函数 //初始化树 void InitializeTree(Tree * ptree) { ptree->root = NULL; ptree->size = 0; } //确认树为满 int TreeIsFull(const Tree * ptree) { if (ptree->size == SIZE) return 1; else return 0; } //确认树为空 int TreeIsEmpty(const Tree * ptree) { if (ptree->size == 0) return 1; else return 0; } //统计项数 int TreeItemCount(const Tree * ptree) { count = 0; CountItem(ptree->root); return count; } //查找项 void FindItem(const Tree * ptree, const Item * pi) { Pair look; int i; look = SeekItem(ptree, pi); if (look.child != NULL) { printf("name: %s\t\tkind: ", look.child->item.name); for (i = 0; i < look.child->item.num; i++) printf("%s ", look.child->item.kind[i]); printf("\n"); } else printf("Can't find the pet.\n"); } //添加项 int AddItem(Tree * ptree, const Item * pi) { Pair look; Trnode * new_node; if (TreeIsFull(ptree)) return 0; look = SeekItem(ptree, pi); if (look.child != NULL) { strcpy(look.child->item.kind[look.child->item.num], pi->kind[0]); (look.child->item.num)++; return 1; } else { new_node = MakeNode(pi); if (new_node == NULL) { fprintf(stderr, "Could't eate node\n"); return 0; } ptree->size++; if (ptree->root == NULL) ptree->root = new_node; else AddNode(new_node, ptree->root); } return 1; } //删除项 int DelItem(Tree * ptree, const Item * pi) { Pair look; look = SeekItem(ptree, pi); if (look.child == NULL) return 0; if (look.parent == NULL) DeleteNode(&ptree->root); else if (look.parent->left == look.child) DeleteNode(&look.parent->left); else DeleteNode(&look.parent->right); ptree->size--; return 1; } //遍历树 void Traverse(const Tree * ptree, void (*pfun)(Item item)) { if (ptree != NULL) InOrder(ptree->root, pfun); } //清空树 void DeleteAll(Tree * ptree) { if (ptree != NULL) DeleteAllNodes(ptree->root); ptree->root = NULL; ptree->size = 0; } //局域函数 //寻找项 static Pair SeekItem(const Tree * ptree, const Item * pi) { Pair look; look.parent = NULL; look.child = ptree->root; if (look.child == NULL) return look; while (look.child != NULL) { if (ToLeft(pi, &(look.child->item))) { look.parent = look.child; look.child = look.child->left; } else if (ToRight(pi, &(look.child->item))) { look.parent = look.child; look.child = look.child->right; } else break; } return look; } //项在左边 static int ToLeft(const Item * p1, const Item * p2) { if (strcmp(p1->name, p2->name) < 0) return 1; else return 0; } //项在右边 static int ToRight(const Item * p1, const Item * p2) { if (strcmp(p1->name, p2->name) > 0) return 1; else return 0; } static Trnode * MakeNode(const Item * item) { Trnode * pnode; pnode = (Trnode *) malloc(sizeof(Trnode)); if (pnode != NULL) { pnode->item = *item; pnode->left = NULL; pnode->right = NULL; } return pnode; } static void AddNode(Trnode * new_node, Trnode * root) { if (ToLeft(&(new_node->item), &(root->item))) { if (root->left == NULL) root->left = new_node; else AddNode(new_node, root->left); } else if (ToRight(&(new_node->item), &(root->item))) { if (root->right == NULL) root->right = new_node; else AddNode(new_node, root->right); } else { fprintf(stderr, "location error in AddNode().\n"); exit(1); } } //ptr 是父节点指向目标节点的指针的地址 static void DeleteNode(Trnode * * ptr) { Trnode * pnode; if ((*ptr)->left == NULL) { pnode = *ptr; *ptr = (*ptr)->right; free(pnode); } else if ((*ptr)->right == NULL) { pnode = *ptr; *ptr = (*ptr)->left; free(pnode); } else { for (pnode = (*ptr)->left; pnode->right != NULL; pnode = pnode->right) continue; pnode->right = (*ptr)->right; pnode = (*ptr); *ptr = (*ptr)->left; free(pnode); } } static void InOrder(Trnode * root, void (*pfun)(Item item)) { if (root != NULL) { InOrder(root->left, pfun); (*pfun)(root->item); InOrder(root->right, pfun); } } static void DeleteAllNodes(Trnode * root) { Trnode * pright; if (root != NULL) { pright = root->right; DeleteAllNodes(root->left); free(root); DeleteAllNodes(pright); } } static void CountItem(Trnode * root) { if (root != NULL) { CountItem(root->left); count += root->item.num; CountItem(root->right); } } ================================================ FILE: Chapter_17/8pet/pet.h ================================================ #ifndef WORD_H_ #define WORD_H_ #define MAX 10 #define LEN 40 #define SIZE 100 typedef struct item { char name[LEN]; char kind[MAX][LEN]; int num; } Item; typedef struct trnode { Item item; struct trnode * left; struct trnode * right; } Trnode; typedef struct tree { Trnode * root; int size; } Tree; //初始化树 void InitializeTree(Tree * ptree); //确认树为满 int TreeIsFull(const Tree * ptree); //确认树为空 int TreeIsEmpty(const Tree * ptree); //统计项数 int TreeItemCount(const Tree * ptree); //查找项 void FindItem(const Tree * ptree, const Item * item); //添加项 int AddItem(Tree * ptree, const Item * pi); //删除项 int DelItem(Tree * ptree, const Item * pi); //遍历树 void Traverse(const Tree * ptree, void (*pfun)(Item item)); //清空树 void DeleteAll(Tree * ptree); #endif ================================================ FILE: README.md ================================================ # C-Primer-Plus C Primer Plus第六版中文版习题答案 本答案为初学编程时记录,在语法、注释规范,代码风格,解题思路上可能并非最优,所以欢迎大家一起共建。 如果代码有错误或待优化之处,可以提出 [Issues](https://github.com/zhayujie/C-Primer-Plus/issues) 一起讨论,也可以发起 [PR](https://github.com/zhayujie/C-Primer-Plus/pulls) 提交你的代码。