cprimerplus第编程练习答案已_第1页
cprimerplus第编程练习答案已_第2页
cprimerplus第编程练习答案已_第3页
cprimerplus第编程练习答案已_第4页
cprimerplus第编程练习答案已_第5页
免费预览已结束,剩余39页可下载查看

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Chapter 2ProgrammingExercisesPE 2-1/* Programming Exercise 2-1 */ #include <> int main(void) printf("Gustav Mahlern"); printf("GustavnMahlern"); printf("Gustav "); printf("Mahlern"); return 0;PE 2-3/* Programming Exercise 2-3 */ #include <> int mai

2、n(void) int ageyears; /* age in years */ int agedays; /* age in days */* large ages may require the long type */ ageyears = 101; agedays = 365 * ageyears;printf("An age of %d years is %d days.n", ageyears, agedays); return 0; PE 2-4/* Programming Exercise 2-4 */ #include <> void joll

3、y(void); void deny(void); int main(void) jolly(); 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");PE 2-6/* Programming Exercise 2-6 */ #include <> int main(void) int toes;toes

4、= 10;printf("toes = %dn", toes);printf("Twice toes = %dn", 2 * toes); printf("toes squared= %dn", toes * toes); return 0;/* or create two more variables, set them to 2 * toes and toes * toes */PE 2-8/* Programming Exercise 2-8 */#include <> void one_three(void); v

5、oid two(void);int main(void)printf("starting now:n"); one_three(); printf("done!n"); return 0;void one_three(void)printf("onen"); two();printf("threen");void two(void)printf("twon");ExercisesProgrammingChapter 3PE 3-2/* Programming Exercise 3-2 */ #i

6、nclude <> int main(void) int ascii;printf("Enter an ASCII code: "); scanf("%d", &ascii); printf("%d is the ASCII code for %c.n", ascii, ascii); return 0;PE 3-4/* Programming Exercise 3-4 */ #include <> int main(void) float num;printf("Enter a floati

7、ng-point value: "); scanf("%f", &num); printf("fixed-point notation: %fn", num);printf("exponential notation: %en", num); printf("p notation: %an", num); return 0;PE 3-6/* Programming Exercise 3-6 */ #include <> int main(void) float mass_mol = ;

8、 /* mass of water molecule in grams */ float mass_qt = 950; /* mass of quart of water in grams */ float quarts; float molecules;printf("Enter the number of quarts of water: "); scanf("%f", &quarts); molecules = quarts * mass_qt / mass_mol;ProgrammingExercisesprintf("%f q

9、uarts of water contain %e molecules.n", quarts, molecules); return 0; Chapter 4PE 4-1/* Programming Exercise 4-1 */ #include <> int main(void) char fname40; char lname40;printf("Enter your first name: "); scanf("%s", fname); printf("Enter your last name: ");

10、scanf("%s", lname); printf("%s, %sn", lname, fname); return 0;PE 4-4/* Programming Exercise 4-4 */ #include <> int main(void) float height; char name40;printf("Enter your height in inches: "); scanf("%f", &height); printf("Enter your name: "

11、;); scanf("%s", name);printf("%s, you are %.3f feet talln", name, height / ; return 0;PE4-7/* Programming Exercise 4-7 */ #include <> #include <> int main(void) float ot_f = / ; double ot_d =/ ; printf(" float values: ");printf("%.4f %.12f %.16fn",

12、 ot_f, ot_f, ot_f); printf("double values: "); printf("%.4f %.12f %.16fn", ot_d, ot_d, ot_d);printf("FLT_DIG: %dn", FLT_DIG); printf("DBL_DIG: %dn", DBL_DIG); Chapter PE5-return 0;ProgrammingExercises-1/* Programming Exercise 5-1 */ #include <> int main(

13、void) const int minperhour = 60; int minutes, hours, mins;printf("Enter the number of minutes to convert: "); scanf("%d", &minutes); while (minutes > 0 ) hours = minutes / minperhour; mins = minutes % minperhour;printf("%d minutes = %d hours, %d minutesn", minute

14、s, hours, mins); printf("Enter next minutes value (0 to quit): "); scanf("%d", &minutes); printf("Byen");return 0;PE5-3/* Programming Exercise 5-3 */ #include <> int main(void) const int daysperweek = 7; int days, weeks, day_rem;printf("Enter the number o

15、f days: "); scanf("%d", &days); while (days > 0) weeks = days / daysperweek; day_rem = days % daysperweek;days,printf("%d days are %d weeks and %d days.n", weeks, day_rem);scanf("%d", &days);printf("Enter the number of days (0 or less to end): "

16、;); printf("Done!n"); return 0;PE 5-5/* Programming Exercise 5-5 */ #include <> int main(void) /* finds sum of first n integers */ int count, sum;int n;printf("Enter the upper limit: "); scanf("%d",&n); count = 0; sum = 0; while (count+ < n) sum = sum + cou

17、nt; printf("sum = %dn", sum); return 0;PE5-7/* Programming Exercise 5-7 */ #include <>void showCube(double x);int main(void) /* finds cube of entered number */ double val;printf("Enter a floating-point value: ");scanf("%lf", &val); showCube(val); return 0; voi

18、d showCube(double x)printf("The cube of %e is %e.n", x, x*x*x );Chapter 6PE6-1/* */* this implementation assumes the character codes */* are sequential, as they are in ASCII. */ #include <> #define SIZE 26 int main( void ) char lcaseSIZE; int i;for (i = 0; i < SIZE; i+) lcasei= &#

19、39;a' + i; for (i = 0; i < SIZE; i+) printf("%c", lcasei); printf("n"); return 0;PE6-3/* */* this implementation assumes the character codes */* are sequential, as they are in ASCII. */ #include <> int main( void ) char let = 'F' char start; char end;for (end

20、 = let; end >= 'A' end-)for (start = let; start >= end; start-) printf("%c", start); printf("n");0;PEProgrammingExercisesreturn6- -6/* */ #include <> int main( void ) int lower, upper, index; int square, cube;printf("%d ", valsi); printf("n"

21、;);printf("Enter starting integer: "); scanf("%d", &lower); printf("Enter ending integer: "); scanf("%d", &upper);printf("%5s %10s %15sn", "num", "square", "cube"); for (index = lower; index <= upper; index+)

22、square = index * index; cube = index * square;printf("%5d %10d %15dn", index, square, cube); return 0; PE 6-8/* */ #include <> int main( void ) double n, m; double res;printf("Enter a pair of numbers: ");while (scanf("%lf %lf", &n, &m) = 2)res = (n - m) /

23、(n * m);printf("(%.3g - %.3g)/(%.3g*%.3g) = %.5gn", n, m, n, m, res); printf("Enter next pair (non-numeric to quit): ");return 0;PE6- 11/* */ #include <> #define SIZE 8 int main( void ) int valsSIZE; int i;printf("Please enter %d integers.n", SIZE); for (i = 0;i &

24、lt; SIZE; i+) scanf("%d", &valsi);printf("Here, in reverse order, are the values you entered:n"); for (i = SIZE - 1; i >= 0; i-) return 0;13PE6-/* */ /* This version starts with the 0 power */#include <> #define SIZE 8 int main( void )int twopowsSIZE; int i;int value

25、 = 1; /* 2 to the 0 */for (i = 0; i < SIZE; i+) twopowsi = value; value *= 2;i+; return 0;i = do printf("%d ", twopowsi); while (i < SIZE); printf("n");0;PE 6- 14/* */ /* Programming Exercise 6-14 */ #include <> #define SIZE 8 int main(void) double arrSIZE; double arr

26、_cumulSIZE; int i;printf("Enter %d numbers:n", SIZE);for (i = 0; i < SIZE; i+)printf("value #%d: ", i + 1); scanf("%lf", &arri); /* or scanf("%lf", arr + i); */ arr_cumul0 = arr0; /* set first element */ for (i = 1; i < SIZE; i+)arr_cumuli = arr_cumu

27、li-1 + arri;printf("n"); for printf("%8g ", printf("n");for (i = 0; i < SIZE; i+) printf("%8g ", arri); (i = 0; i < SIZE; i+) arr_cumuli); return 0; 16PE6-SIMP/* */ #include <> #define RATE #define RATE_COMP #define INIT_AMT int main( void )double

28、daphne = INIT_AMT; double deidre = INIT_AMT; int years = 0;while (deidre <= daphne) daphne += RATE_SIMP * INIT_AMT; deidre += RATE_COMP * deidre;+years; printf("Investment values after %d years:n", years); printf("Daphne: $%.2fn", daphne); printf("Deidre: $%.2fn", de

29、idre); return 0;ProgrammingExercises Chapter 7 PE7-1/* Programming Exercise 7-1 */ #include <> int main(void) char ch; int sp_ct = 0; int nl_ct = 0; int other = 0; while (ch = getchar() != '#') if (ch = ' ') sp_ct+; else if (ch = 'n') nl_ct+; else other+;printf("sp

30、aces: %d, newlines: %d, others: %dn", sp_ct, nl_ct, other); return 0;PE 7-3/* Programming Exercise 7-3 */ #include <> int main(void) int n; double sumeven = ;int ct_even = 0; double sumodd= ; int ct_odd = 0;while (scanf("%d", &n) = 1 && n != 0)if (n % 2 = 0) sumeven

31、+= n;+ct_even;else : putchar('!');+ct1; break;case '!' : putchar('!');putchar('!'); +ct2; break; default : putchar(ch); printf("%d replacement(s) of . with !n", ct1); printf("%d replacement(s) of ! with !n", ct2);return 0;PE 7-7f; taxes: $%.2f; net

32、: $%.2fn", gross, taxes, net); return 0;PE 7-9/* Programming Exercise 7-9 */ #include <> #include <> int main(void)int limit; int num; int div;bool numIsPrime; n"); for (num = 2; num <=limit; num+)for (div = 2, numIsPrime = true; (div * div) <= num; div+) if (num % div =

33、0)numIsPrime = false; if (numIsPrime)printf("%d is prime.n", num);printf("Enter a positive integer (q to quit): ");printf("Done!n");return 0;PE7- 11/* */* Programming Exercise 7-11 */#include <> #include <> int main(void) const double price_artichokes = ; co

34、nst double price_beets = ; const double price_carrots = ; const double DISCOUNT_RATE = ; const double under5 = ; const double under20 = ; const double base20 = ; const double extralb = ;char ch; double lb_artichokes = 0; double lb_beets = 0; double lb_carrots = 0; double lb_temp; double lb_total;dou

35、ble cost_artichokes; double cost_beets; double cost_carrots; double cost_total; double final_total; double discount; double shipping;printf("Enter a to buy artichokes, b for beets, "); printf("c for carrots, q to quit: "); while (ch = getchar() != 'q' && ch != 

36、9;Q') if (ch = 'n') continue; continue; switch (ch)while (getchar() != 'n') ch = tolower(ch);case 'a' : printf("Enter pounds of artichokes: "); scanf("%lf", &lb_temp); lb_artichokes += lb_temp; break;case 'b' : printf("Enter pounds of

37、beets: "); scanf("%lf", &lb_temp);lb_beets += lb_temp;break;case 'c' : printf("Enter pounds of carrots: "); scanf("%lf", &lb_temp); lb_carrots += lb_temp; break;default : printf("%c is not a valid choice.n", ch);printf("Enter a to buy

38、 artichokes, b for beets, "); printf("c for carrots, q to quit: "); cost_artichokes = price_artichokes * lb_artichokes; cost_beets = price_beets * lb_beets; cost_carrots = price_carrots * lb_carrots; cost_total = cost_artichokes + cost_beets + cost_carrots; lb_total = lb_artichokes +

39、lb_beets + lb_carrots; if (lb_total <= 0) shipping = ; else if (lb_total < shipping = under5; else if (lb_total < 20) shipping = under20; elseshipping = base20 + extralb * lb_total; if (cost_total > discount = DISCOUNT_RATE * cost_total; else discount = ;final_total = cost_total + shippi

40、ng - discount; printf("Your order:n"); printf("%.2f lbs of artichokes at $%.2f per pound:$ %.2fn", lb_artichokes, price_artichokes, cost_artichokes); printf("%.2f lbs of beets at $%.2f per pound: $%.2fn",lb_beets, price_beets, cost_beets);printf("%.2f lbs of carrot

41、s at $%.2f per pound: $%.2fn",lb_carrots,price_carrots, cost_carrots); printf("Total cost of vegetables: $%.2fn", cost_total); if (cost_total > 100)Exercisesprintf("Volume discount: $%.2fn", discount); printf("Shipping: $%.2fn", shipping); printf("Total cha

42、rges: $%.2fn", final_total); return 0; ProgrammingChapter 8PE 8-1/* Programming Exercise 8-1 */ #include <>int main(void) int ch; int ct = 0; while (ch = getchar() != EOF) ct+;printf("%d characters readn", ct); return 0;PE8-3/* Programming Exercise 8-3 */* Using eliminates need

43、to assume consecutive coding */#include <> #include <> int main(void) int ch; unsigned long uct =0; unsigned long lct = 0; unsigned long oct = 0;while (ch = getchar() != EOF) if(isupper(ch) uct+; else if(islower(ch) lct+; else oct+;printf("%lu uppercase characters readn", uct);

44、 printf("%lu lowercase characters readn", lct); printf("%lu other characters readn", oct);return 0;/* or you could use if (ch >= 'A' &&ch <= 'Z') uct+;else if (ch >= 'a' && ch <= 'z') lct+;else oct+;*/PE8-5/* Programming

45、 Exercise 8-5 */* - an improved number-guesser */* but relies upon truthful, correct responses */#include <> #include <> int main(void) int high = 100; int low = 1; int guess = (high + low) / 2; char response;printf("Pick an integer from 1 to 100. I will try to guess "); printf

46、("it.nRespond with a y if my guess is right, with"); printf("na h if it is high, and with an l if it is low.n"); printf("Uh.is your number %d?n", guess);while (response = getchar() != 'y') /* get response */if (response = 'n') continue;if (response != &#

47、39;h' && response != 'l')printf("I don't understand that response. Please enter h forn");printf("high, l for low, or y for correct.n"); continue; if (response = 'h') high = guess - 1; else if (response = 'l')low = guess + 1; guess = (high +

48、 low)/ 2;printf("Well, then, is it %d?n", guess); printf("I knew I could do it!n"); return 0;PE 8-7*/ switch (response)/* Programming Exercise 8-7 */ #include <> #include <> #include <> #define BASEPAY1case 'a': pay = BASEPAY1; break; case 'b': p

49、ay = BASEPAY2; break; case 'c': pay = BASEPAY3; break; case 'd': pay = BASEPAY4; break;default : printf("Please enter a, b, c, d, or q.n"); menu();continue; f; taxes: $%.2f; net: $%.2fn", gross, taxes, net); menu(); printf("Done.n"); return 0;void menu(void)

50、printf("*" "*n");printf("Enter the letter corresponding to the desired pay rate"" or action:n");b) $%hrn", BASEPAY1,d) $%hrn", BASEPAY3,BASEPAY2);BASEPAY4);printf("a) $%hrprintf("c) $%hr printf("q) quitn");printf("*" &qu

51、ot;*n");int getfirst(void) int ch;ch = getchar(); while (isspace(ch)ch = getchar();while (getchar() != 'n') continue;ChapterPE 9-return ch;ProgrammingExercises/* Programming Exercise 9-1 */ #include <> double min(double, double); int main(void) double x, y; printf("Enter two

52、numbers (q to quit): "); while (scanf("%lf %lf", &x, &y) = 2) printf("The smaller number is %f.n", min(x,y); printf("Next two values (q to quit): "); printf("Bye!n");return 0;double min(double a, double b)return a < b ? a : b;/* alternative imp

53、lementation double min(double a, double b) if (a < b)return a; elsereturn b;*/PE 9-3/* Programming Exercise 9-3 */#include <>void chLineRow(char ch, int c, int r); int main(void) char ch; int col, row; printf("Enter a character (# to quit): "); while ( (ch = getchar() != '#

54、9;)if (ch = 'n')continue;printf("Enter number of columns and number of rows: ");if(scanf("%d %d", &col, &row) != 2) break; chLineRow(ch, col, row);printf("nEnter next character (# to quit): "); printf("Bye!n");return 0;n", x, y);printf(&qu

55、ot;Next two values (q to quit): ");printf("Bye!n");return 0;void larger_of(double *p1, double *p2) if (*p1 > *p2) *p2 = *p1; else *p1 = *p2;Enter q"); printf(" to quit.n"); while (scanf("%lf%d", &x, &n) = 2)*/ xpow = power(x,n); /* function callprin

56、tf("Enter nextprintf("%.3g to the power %d is %.5gn", x, n, xpow); pair of numbers or q to quit.n"); printf("Hope you enjoyed this power trip - bye!n"); double power(double a, int b) /* function definition double pow = 1; int i; if (b = 0) if (a = 0)printf("0 to th

57、e 0 undefined; using 1 as the valuen"); pow = ; pow = ; else if (b > 0) for(i = 1; i <= b; i+)/* b < 0 */ pow = / power(a, - b);/* return the value of pow */else if (a = 0) pow *= a; else return pow;return 0; */PE 9- 10/* Programming Exercise 9-10 */ #include <> void to_base_n(in

58、t x, int base); int main(void) int number; int b; int count; printf("Enter an integer (q to quit):n"); while (scanf("%d", &number) = 1) printf("Enter number base (2-10): "); while (count = scanf("%d", &b)= 1&& (b < 2 | b > 10) printf(&quo

59、t;base should be in the range 2-10: "); if (count != 1) break;printf("Base %d equivalent: ", b); to_base_n(number, b); putchar('n');printf("Enter an integer (q to quit):n"); printf("Done.n"); return0;void to_base_n(int x, int base) /* recursive function */

60、int r; r = x % base; if (x >= base) to_base_n(x / base, base); putchar('0' + r); return;ExercisesProgrammingChapter 10PE 10-1/* Programming Exercise 10-1 */#include <>#define MONTHS 12 f inches.nn", total/YRS); printf("MONTHLY AVERAGES:nn"); printf(" Jan Feb Mar

61、Apr May Jun Jul Aug Sep Oct "); printf(" Nov Decn"); for (month = 0; month < MONTHS; month+) /* for each month, sum rainfall over years */ for (year =0, subtot =0; year < YRS; year+) subtot += *(*(rain + year) + month); printf("% ", subtot/YRS); printf("n");r

62、eturn 0;PE 10-3/* Programming Exercise 10-3 */#include <>#define LEN 10int max_arr(const int ar, int n); void show_arr(const int ar, int n);int main(void)int origLEN = 1,2,3,4,12,6,7,8,9,10; int max; show_arr(orig, LEN); max = max_arr(orig, LEN);printf("%d = largest valuen", max); return 0;int max_arr(const int ar, int n) int i; int max = ar0;/* don&

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论