C++primer 章节版
- 格式:docx
- 大小:143.49 KB
- 文档页数:41
Chapter 2Programming ExercisesPE 2--‐1/*ProgrammingExercise2-1*/#include<stdio.h>intmain(void){printf("GustavMahler\n");printf("Gustav\nMahler\n");printf("Gustav");printf("Mahler\n");return0;}PE 2--‐3/*ProgrammingExercise2-3*/#include<stdio.h>intmain(void){intageyears;/*ageinyears*/intagedays;/*ageindays*//*largeagesmayrequirethelongtype*/ageyears=101;agedays=365*ag eyears;printf("Anageof%dyearsis%ddays.\n",ageyears,agedays);return0; }PE 2--‐4/*ProgrammingExercise2-4*/#include<stdio.h>voidjolly(void);voiddeny(void);intmain(void){jolly();jolly();jolly();deny();return0;}voidjolly(void){printf("Forhe'sajollygoodfellow!\n");}voiddeny(void){printf("Whichnobodycandeny!\n");}PE 2--‐6/*ProgrammingExercise2-6*/#include<stdio.h>intmain(void){inttoes;toes=10;printf("toes=%d\n",toes);printf("Twicetoes=%d\n",2*toes);printf("toessquared=%d\n",toes*toes);return0;}/*orcreatetwomorevariables,setthemto2*toesandtoes*toes*/ PE 2--‐8/*ProgrammingExercise2-8*/#include<stdio.h>voidone_three(void);voidtwo(void);intmain(void){printf("startingnow:\n");one_three();printf("done!\n");return0;}voidone_three(void){printf("one\n");two();printf("three\n");}voidtwo(void){printf("two\n");}Chapter 3Programming ExercisesPE 3--‐2/*ProgrammingExercise3-2*/#include<stdio.h>intmain(void){intascii;printf("EnteranASCIIcode:");scanf("%d",&ascii);printf("%distheASCIIcodefor%c.\n",ascii,ascii);return0; }PE 3--‐4/*ProgrammingExercise3-4*/#include<stdio.h>intmain(void){floatnum;printf("Enterafloating-pointvalue:");scanf("%f",&num); printf("fixed-pointnotation:%f\n",num);printf("exponentialnotation:%e\n",num);printf("pnotation:%a\n",num);return0;}PE 3--‐6/*ProgrammingExercise3-6*/#include<stdio.h>intmain(void){floatmass_mol=3.0e-23;/*massofwatermoleculeingrams*/floatmass_qt=950;/*massofquartofwat eringrams*/floatquarts;floatmolecules;printf("Enterthenumberofquartsofwater:");scanf("%f",&quarts);molecules=quarts*mass_qt/mass_mol;printf("%fquartsofwatercontain%emolecules.\n",quarts,molecules);return0; }Chapter 4Programming ExercisesPE 4--‐1/*ProgrammingExercise4-1*/#include<stdio.h>intmain(void){charfname[40];charlname[40];printf("Enteryourfirstname:");scanf("%s",fname);printf("Enteryourlastname:");scanf("%s",lname);printf("%s,%s\n",lname,fname);return0;}PE 4--‐4/*ProgrammingExercise4-4*/#include<stdio.h>intmain(void){floatheight;charname[40];printf("Enteryourheightininches:");scanf("%f",&height);printf("Enteryourname:");scanf("%s",name);printf("%s,youare%.3ffeettall\n",name,height/12.0);return0;}PE 4--‐7/*ProgrammingExercise4-7*/#include<stdio.h>#include<float.h>intmain(void){floatot_f=1.0/3.0;doubleot_d=1.0/3.0;printf("floatvalues:");printf("%.4f%.12f%.16f\n",ot_f,ot_f,ot_f);printf("doublevalues:");printf("%.4f%.12f%.16f\n",ot_d,ot_d,ot_d);printf("FLT_DIG:%d\n",FLT_DIG);printf("DBL_DIG:%d\n",DBL_DIG);return0;}Chapter 5Programming ExercisesPE 5--‐1/*ProgrammingExercise5-1*/#include<stdio.h>intmain(void){constintminperhour=60;intminutes,hours,mins;printf("Enterthenumberofminutestoconvert:");scanf("%d",&minutes);while(minutes>0){hours=minutes/minperhour;mins=minutes%minperhour;printf("%dminutes=%dhours,%dminutes\n",minutes,hours,mins);printf("Enterne xtminutesvalue(0toquit):");scanf("%d",&minutes);}printf("Bye\n");return0;}PE 5--‐3/*ProgrammingExercise5-3*/#include<stdio.h>intmain(void){constintdaysperweek=7;intdays,weeks,day_rem;printf("Enterthenumberofdays:");scanf("%d",&days);while(days>0){weeks=days/daysperweek;day_rem=days%daysperweek;printf("%ddaysare%dweeksand%ddays.\n",days,weeks,day_rem);printf("Enterthenumberofdays(0orlesstoend):");scanf("%d",&days);}printf("Done!\n");return0;}PE 5--‐5/*ProgrammingExercise5-5*/#include<stdio.h>intmain(void)/*findssumoffirstnintegers*/{intcount,sum;intn;printf("Entertheupperlimit:");scanf("%d",&n);count=0;sum=0;while(count++<n)sum=sum+count;printf("sum=%d\n",sum);return0;}PE 5--‐7/*ProgrammingExercise5-7*/#include<stdio.h>voidshowCube(doublex);intmain(void)/*findscubeofenterednumber*/ {doubleval;printf("Enterafloating-pointvalue:");scanf("%lf",&val);showCube(val);r eturn0;}voidshowCube(doublex){printf("Thecubeof%eis%e.\n",x,x*x*x);}Chapter 6Programming ExercisesPE 6--‐1/*pe6-1.c*//*thisimplementationassumesthecharactercodes*/ /*aresequential,astheyareinASCII.*/#include<stdio.h>#defineSIZE26intmain(void){charlcase[SIZE];inti;for(i=0;i<SIZE;i++)lcase[i]='a'+i;for(i=0;i<SIZE;i++)printf("%c",lcase[i]);printf("\n");return0;}PE 6--‐3/*pe6-3.c*//*thisimplementationassumesthecharactercodes*/ /*aresequential,astheyareinASCII.*/#include<stdio.h>intmain(void){charlet='F';charstart;charend;for(end=let;end>='A';end--){for(start=let;start>=end;start--)printf("%c",start);printf("\n");}return0;}PE 6--‐6/*pe6-6.c*/#include<stdio.h>intmain(void){intlower,upper,index;intsquare,cube;printf("Enterstartinginteger:");scanf("%d",&lower);printf("Enterendinginteger:");scanf("%d",&upper);printf("%5s%10s%15s\n","num","square","cube");for(index=lower;index<=upper;index++){square=index*index;cube=index*square;printf("%5d%10d%15d\n",index,square,cube);}return0;}PE 6--‐8/*pe6-8.c*/#include<stdio.h>intmain(void){doublen,m;doubleres;printf("Enterapairofnumbers:");while(scanf("%lf%lf",&n,&m)==2){res=(n-m)/(n*m);printf("(%.3g-%.3g)/(%.3g*%.3g)=%.5g\n",n,m,n,m,res);printf("Enternextpair(non-numerictoquit):");}return0;}PE 6--‐11/*pe6-11.c*/#include<stdio.h>#defineSIZE8intmain(void){intvals[SIZE];inti;printf("Pleaseenter%dintegers.\n",SIZE);for(i=0;i<SIZE;i++)scanf("%d",&vals[i]);printf("Here,inreverseorder,arethevaluesyouentered:\n");for(i=SIZE -1;i>=0;i--)printf("%d",vals[i]);printf("\n");return0;}PE 6--‐13/*pe6-13.c*//*Thisversionstartswiththe0power*/#include<stdio.h>#defineSIZE8intmain(void){inttwopows[SIZE];inti;intvalue=1;/*2tothe0*/for(i=0;i<SIZE;i++){twopows[i]=value;value*=2;}i=0;do{printf("%d",twopows[i]);i++;}while(i<SIZE);printf("\n");return0;}PE 6--‐14/*pe-14.c*//*ProgrammingExercise6-14*/#include<stdio.h>#defineSIZE8intmain(void){doublearr[SIZE];doublearr_cumul[SIZE];inti;printf("Enter%dnumbers:\n",SIZE);for(i=0;i<SIZE;i++){printf("value#%d:",i+1);scanf("%lf",&arr[i]);/*orscanf("%lf",arr+i);*/}arr_cumul[0]=arr[0];/*setfirstelement*/for(i=1;i<SIZE;i++) arr_cumul[i]=arr_cumul[i-1]+arr[i];for(i=0;i<SIZE;i++)printf("%8g",arr[i]);printf("\n");for(i=0;i<SIZE;i++)printf("%8g",arr_cumul[i]);printf("\n");return0;}PE 6--‐16/*pe6-16.c*/#include<stdio.h>#defineRATE_SIMP0.10#defineRATE_COMP0.05#defineINIT_AMT100.0intmain(void){doubledaphne=INIT_AMT;doubledeidre=INIT_AMT;intyears=0;while(deidre<=daphne){daphne+=RATE_SIMP*INIT_AMT;deidre+=RATE_COMP*deidre;++years;}printf("Investmentvaluesafter%dyears:\n",years);printf("D aphne:$%.2f\n",daphne);printf("Deidre:$%.2f\n",deidre);return0;}Chapter 7Programming ExercisesPE 7--‐1/*ProgrammingExercise7-1*/#include<stdio.h>intmain(void){charch;intsp_ct=0;intnl_ct=0;intother=0;while((ch=getchar())!='#'){if(ch=='')sp_ct++;elseif(ch=='\n')nl_ct++;elseother++;}printf("spaces:%d,newlines:%d,others:%d\n",sp_ct,nl_ct,other); return0;}PE 7--‐3/*ProgrammingExercise7-3*/#include<stdio.h>intmain(void){intn;doublesumeven=0.0;intct_even=0;doublesumodd=0.0;intct_odd=0;while(scanf("%d",&n)==1&&n!=0){if(n%2==0){sumeven+=n;++ct_even;}else//n%2iseither1or-1{sumodd+=n;++ct_odd;}}printf("Numberofevens:%d",ct_even);if(ct_even>0)printf("average:%g",sumeven/ct_even);putchar('\n');printf("Numberofodds:%d",ct_odd);if(ct_odd>0)printf("average:%g",sumodd/ct_odd);putchar('\n');printf("\ndone\n");return0;}PE 7--‐5/*ProgrammingExercise7-5*/#include<stdio.h>intmain(void){charch;intct1=0;intct2=0;while((ch=getchar())!='#'){switch(ch){case'.':putchar('!');++ct1;break;case'!':putchar('!');putchar('!');++ct2;break;default:putchar(ch);}}printf("%dreplacement(s)of.with!\n",ct1);printf("%dreplacement(s)of!with!!\n",ct2);return0;}PE 7--‐7//ProgrammingExercise7-7#include<stdio.h>#defineBASEPAY10//$10perhour#defineBASEHRS40//hoursatbasepay#defineOVERTIME1.5//1.5time#defineAMT1300//1stratetier#defineAMT2150//2stratetier#defineRATE10.15//ratefor1sttier#defineRATE20.20//ratefor2ndtier#defineRATE30.25//ratefor3rdtierintmain(void){doublehours;doublegross;doublenet;doubletaxes;printf("Enterthenumberofhoursworkedthisweek:");scanf("%lf",&hours);if(hours<=BASEHRS)gross=hours*BASEPAY;elsegross=BASEHRS*BASEPAY+(hours-BASEHRS)*BASEPAY*OVERTIME;if(gross<=AMT1)taxes=gross*RATE1;elseif(gross<= AMT1+AMT2)taxes=AMT1*RATE1+(gross-AMT1)*RATE2;elsetaxes=AMT1*RATE1+AMT2*RATE2+(gross-AMT1-AMT2)*RATE3;net=gross-taxes; printf("gross:$%.2f;taxes:$%.2f;net:$%.2f\n",gross,taxes,net);return0;}PE 7--‐9/*ProgrammingExercise7-9*/#include<stdio.h>#include<stdbool.h>intmain(void){intlimit;intnum;intdiv;boolnumIsPrime;//useintifstdbool.hnotavailableprintf("Enterapositiveinteger:");while(scanf("%d",&limit)==1&&limit>0){if(limit>1)printf("Herearetheprimenumbersupthrough%d\n",limit);elseprintf("Noprimes.\n");for(num=2;num<=limit;num++){for(div=2,numIsPrime=true;(div*div)<=num;div++)if(num%div==0)numIsPrime =false;if(numIsPrime)printf("%disprime.\n",num);}printf("Enterapositiveinteger(qtoquit):");}printf("Done!\n");return0;}PE 7--‐11/*pe7-11.c*//*ProgrammingExercise7-11*/#include<stdio.h>#include<ctype.h>intmain(void){constdoubleprice_artichokes=2.05;constdoubleprice_beets=1.15;constdoubleprice_carrots=1.09;constdoubleDISCOUNT_RATE=0.05;constdoubleunder5=6.50;constdoubleunder20=14.00;constdoublebase20=14.00;constdoubleextralb=0.50;charch;doublelb_artichokes=0;doublelb_beets=0;doublelb_carrots=0;doublelb_temp;doublelb_total;doublecost_artichokes;doublecost_beets;doublecost_carrots;doublecost_total;doublefinal_total;doublediscount;doubleshipping;printf("Enteratobuyartichokes,bforbeets,");printf("cforcarrots,qtoquit:");while((ch=getchar())!='q'&&ch!='Q'){if(ch=='\n')continue;while(getchar()!='\n')continue;ch=tolower(ch);switch(ch){case'a':printf("Enterpoundsofartichokes:");scanf("%lf",&lb_ temp);lb_artichokes+=lb_temp;break;case'b':printf("Enterpoundsofbeets:");scanf("%lf",&lb_temp);lb_beets+=lb_temp;break;case'c':printf("Enterpoundsofcarrots:");scanf("%lf",&lb_t emp);lb_carrots+=lb_temp;break;default:printf("%cisnotavalidchoice.\n",ch);}printf("Enteratobuyartichokes,bforbeets,");printf("cforcarrots,q toquit:");}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+lb_beets+lb_carrots;if(lb_total<=0)shipping=0.0;elseif(lb_total<5.0)shipping=under5;elseif(lb_total<20)shipping=under20;elseshipping=base20+extralb*lb_total;if(cost_total>100.0)discount=DISCOUNT_RATE*cost_total;elsediscount=0.0;final_total=cost_total+shipping-discount;printf("Yourorder:\n");printf("%.2flbsofartichokesat$%.2fperpound:$%.2f\n",lb_artich okes,price_artichokes,cost_artichokes);printf("%.2flbsofbeetsat$%.2fperpound:$%.2f\n",lb_beets,price_beets,cost_beets);printf("%.2flbsofcarrotsat$%.2fperpound:$%.2f\n",lb_carrots,price_carrots,cost_carrots);printf("Totalcostofvegetables:$%.2f\n ",cost_total);if(cost_total>100)printf("Volumediscount:$%.2f\n",discount);printf("Shipping:$%.2f\n",shipping);printf("Totalcharges:$%.2f\n",final_total);return0;}Chapter 8Programming ExercisesPE 8--‐1/*ProgrammingExercise8-1*/#include<stdio.h>intmain(void){intch;intct=0;while((ch=getchar())!=EOF)ct++;printf("%dcharactersread\n",ct);return0;}PE 8--‐3/*ProgrammingExercise8-3*//*Usingctype.heliminatesneedtoassumeconsecutivecoding*/#include<stdio.h>#include<ctype.h>intmain(void){intch;unsignedlonguct=0;unsignedlonglct=0;unsignedlongoct=0;while((ch=getchar())!=EOF)if(isupper(ch))uct++;elseif(islower(ch))lct++;elseoct++;printf("%luuppercasecharactersread\n",uct);printf("%lulowercas echaractersread\n",lct);printf("%luothercharactersread\n",oct);return0;}/*oryoucoulduseif(ch>='A'&&ch<='Z')uct++;elseif(ch>='a'&&ch<='z')lct++;elseoct++;*/PE 8--‐5/*ProgrammingExercise8-5*//*binaryguess.c--animprovednumber-guesser*//*butreliesupontruthful,correctresponses*/#include<stdio.h>#include<ctype.h>intmain(void){inthigh=100;intlow=1;intguess=(high+low)/2;charresponse;printf("Pickanintegerfrom1to100.Iwilltrytoguess");printf("it.\nRespondw ithayifmyguessisright,with");printf("\nahifitishigh,andwithanlifitislow .\n");printf("Uh...isyournumber%d\n",guess);while((response=getchar())!='y')/*getresponse*/{if(response=='\n')continue;if(response!='h'&&response!='l')printf("Idon'tunderstandthatresponse.Pleaseenterhfor\n");printf("high,lfor low,oryforcorrect.\n");continue;}if(response=='h')high=guess-1;elseif(response=='l')low=guess+1;guess=(high+low)/2;printf("Well,then,isit%d\n",guess);}printf("IknewIcoulddoit!\n");return0;}PE 8--‐7/*ProgrammingExercise8-7*/#include<stdio.h>#include<ctype.h>#include<stdio.h>#defineBASEPAY18.75//$8.75perhour#defineBASEPAY29.33//$9.33perhour#defineBASEPAY310.00//$10.00perhour#defineBASEPAY411.20//$11.20perhour#defineBASEHRS40//hoursatbasepay#defineOVERTIME1.5//1.5time#defineAMT1300//1stratetier#defineAMT2150//2stratetier#defineRATE10.15//ratefor1sttier#defineRATE20.20//ratefor2ndtier#defineRATE30.25//ratefor3rdtierintgetfirst(void);voidmenu(void);intmain(void){doublehours;doublegross;doublenet;doubletaxes;doublepay;charresponse;menu();while((response=getfirst())!='q'){if(response=='\n')/*skipovernewlines*/continue;response=tolower(response);/*acceptAasa,etc.*/switch(response){case'a':pay=BASEPAY1;break;case'b':pay=BASEPAY2;break;case'c':pay=BASEPAY3;break;case'd':pay=BASEPAY4;break;default:printf("Pleaseentera,b,c,d,orq.\n");menu();continue;//gotobeginningofloopprintf("Enterthenumberofhoursworkedthisweek:");scanf("%lf",&hours);if(hours<=BASEHRS)gross=hours*pay;elsegross=BASEHRS*pay+(hours-BASEHRS)*pay*OVERTIME;if(gross<=AMT1)taxes=gross*RATE1;elseif(gross<= AMT1+AMT2)taxes=AMT1*RATE1+(gross-AMT1)*RATE2;elsetaxes=AMT1*RATE1+AMT2*RATE2+(gross-AMT1-AMT2)*RATE3;net=gross-taxes; printf("gross:$%.2f;taxes:$%.2f;net:$%.2f\n",gross,taxes,net);menu();} printf("Done.\n");return0;}voidmenu(void){printf("********************************************************""*********\n");printf("Enterthelettercorrespondingtothedesiredpayrate""oraction:\n");printf("a)$%4.2f/hrb)$%4.2f/hr\n",BASEPAY1,BASEPAY2);printf("c)$%5.2f/hrd)$%5.2f/hr\n",BASEPAY3,BASEPAY4);printf("q)quit\n");printf("********************************************************""*********\n");}intgetfirst(void){intch;ch=getchar();while(isspace(ch))ch=getchar();while(getchar()!='\n')continue;returnch;}Chapter 9Programming ExercisesPE 9--‐1/*ProgrammingExercise9-1*/#include<stdio.h>doublemin(double,double);intmain(void){doublex,y;printf("Entertwonumbers(qtoquit):");while(scanf("%lf%lf",&x,&y)==2){printf("Thesmallernumberis%f.\n",min(x,y));printf("Nexttwovalues(qtoquit):");}printf("Bye!\n");return0;}doublemin(doublea,doubleb){returna<ba:b;}/*alternativeimplementationdoublemin(doublea,doubleb){if(a<b)returna;elsereturnb;}*/PE 9--‐3/*ProgrammingExercise9-3*/#include<stdio.h>voidchLineRow(charch,intc,intr);intmain(void){charch;intcol,row;printf("Enteracharacter(#toquit):");while((ch=getchar())!='#'){if(ch=='\n')continue;printf("Enternumberofcolumnsandnumberofrows:");if(scanf("%d%d" ,&col,&row)!=2)break;chLineRow(ch,col,row);printf("\nEnternextcharacter(#toquit):");}printf("Bye!\n");return0;}//startrowsandcolsat0voidchLineRow(charch,intc,intr){intcol,row;for(row=0;row<r;row++){for(col=0;col<c;col++)putchar(ch);putchar('\n');}return;}PE 9--‐5/*ProgrammingExercise9-5*/#include<stdio.h>voidlarger_of(double*p1,double*p2);intmain(void){doublex,y;printf("Entertwonumbers(qtoquit):");while(scanf("%lf%lf",&x,&y)==2){larger_of(&x,&y);printf("Themodifiedvaluesare%fand%f.\n",x,y);printf("Nexttwovalues(qtoq uit):");}printf("Bye!\n");return0;}voidlarger_of(double*p1,double*p2){if(*p1>*p2)*p2=*p1;else*p1=*p2;}//alternatively:/*voidlarger_of(double*p1,double*p2){*p1=*p2=*p1>*p2*p1:*p2;}*/PE 9--‐8/*ProgrammingExercise9-8*/#include<stdio.h>doublepower(doublea,intb);/*ANSIprototype*/intmain(void){doublex,xpow;intn;printf("Enteranumberandtheintegerpower");printf("towhich\nthenumberwillberaised.Enterq");printf("toquit.\n");while(scanf("%lf%d",&x,&n)==2){xpow=power(x,n);/*functioncall*/printf("%.3gtothepower%dis%.5g\n",x,n,xpow);printf("Enternextpairofnumbersorqtoquit.\n");}printf("Hopeyouenjoyedthispowertrip--bye!\n");return0;}doublepower(doublea,intb)/*functiondefinition*/{doublepow=1;inti;if(b==0){if(a==0)printf("0tothe0undefined;using1asthevalue\n");pow=1.0;}elseif(a==0)pow=0.0;elseif(b>0)for(i=1;i<=b;i++)pow*=a;else/*b<0*/pow=1.0/power(a,-b);returnpow;/*returnthevalueofpow*/}PE 9--‐10/*ProgrammingExercise9-10*/#include<stdio.h>voidto_base_n(intx,intbase);intmain(void){intnumber;intb;intcount;printf("Enteraninteger(qtoquit):\n");while(scanf("%d",&number)==1){printf("Enternumberbase(2-10):");while((count=scanf("%d",&b))==1&&(b<2||b>10)){printf("baseshouldbeintherange2-10:");}if(count!=1)break;printf("Base%dequivalent:",b);to_base_n(number,b);putchar('\n');printf("Enteraninteger(qtoquit):\n");}printf("Done.\n");return0;}voidto_base_n(intx,intbase)/*recursivefunction*/{intr;r=x%base;if(x>=base)to_base_n(x/base,base);putchar('0'+r);return;}Chapter 10 Programming ExercisesPE 10--‐1/*ProgrammingExercise10-1*/#include<stdio.h>#defineMONTHS12//numberofmonthsinayear#defineYRS5// numberofyearsofdataintmain(void){//initializingrainfalldatafor2010-2014constfloatrain[YRS][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}};intyear,month;floatsubtot,total;printf("YEARRAINFALL(inches)\n");for(year=0,total=0;year<YRS;year++){/*foreachyear,sumrainfallforeachmonth*/for(month=0,subtot=0;mont h<MONTHS;month++)subtot+=*(*(rain+year)+month);printf("%5d%15.1f\ n",2010+year,subtot);total+=subtot;/*totalforallyears*/}printf("\nTheyearlyaverageis%.1finches.\n\n",total/YRS);printf("MONTHLY AVERAGES:\n\n");printf("JanFebMarAprMayJunJulAugSepOct");printf("NovDec\n");for(month=0;month<MONTHS;month++){/*foreachmonth,sumrainfalloveryears*/for(year=0,subtot=0;year<YRS;year++)subtot+=*(*(rain+year)+month);printf("%4.1f",subtot/YRS);}printf("\n");return0;}PE 10--‐3/*ProgrammingExercise10-3*/#include<stdio.h>#defineLEN10intmax_arr(constintar[],intn);voidshow_arr(constintar[],intn);intmain(void){intorig[LEN]={1,2,3,4,12,6,7,8,9,10};intmax;show_arr(orig,LEN);max=max_arr(orig,LEN);printf("%d=largestvalue\n",max);return0;}intmax_arr(constintar[],intn){inti;intmax=ar[0];/*don'tuse0asinitialmaxvalue--failsifallarrayvaluesareneg*/for(i=1;i<n;i++)if(max<ar[i])max=ar[i];returnmax;}voidshow_arr(constintar[],intn){inti;for(i=0;i<n;i++)printf("%d",ar[i]);putchar('\n');}PE 10--‐5/*ProgrammingExercise10-5*/#include<stdio.h>#defineLEN10doublemax_diff(constdoublear[],intn);voidshow_arr(constdoublear[],intn);intmain(void){doubleorig[LEN]={1.1,2,3,4,12,61.3,7,8,9,10};doublemax;show_arr(orig,LEN);max=max_diff(orig,LEN);printf("%g=maximumdifference\n",max);return0;}doublemax_diff(constdoublear[],intn){inti;doublemax=ar[0];doublemin=ar[0];for(i=1;i<n;i++){if(max<ar[i])max=ar[i];elseif(min>ar[i])min=ar[i];}returnmax-min;}voidshow_arr(constdoublear[],intn){inti;for(i=0;i<n;i++)printf("%g",ar[i]);putchar('\n');}PE 10--‐8/*ProgrammingExercise10-8*/#include<stdio.h>#defineLEN17#defineLEN23voidcopy_arr(intar1[],constintar2[],intn);voidshow_arr (constint[],int);intmain(void){intorig[LEN1]={1,2,3,4,5,6,7};intcopy[LEN2];show_arr(orig,LEN1);copy_arr(copy,orig+2,LEN2);show_arr(copy,LEN2);return0;}voidcopy_arr(intar1[],constintar2[],intn){inti;for(i=0;i<n;i++)ar1[i]=ar2[i];}voidshow_arr(constintar[],intn){inti;for(i=0;i<n;i++)printf("%d",ar[i]);putchar('\n');}PE 10--‐11/*ProgrammingExercise10-11*/#include<stdio.h>#defineROWS3#defineCOLS5voidtimes2(intar[][COLS],intr);voidshowarr2(intar[][COLS],intr);intmain(void){intstuff[ROWS][COLS]={{1,2,3,4,5},{6,7,8,-2,10},{11,12,13,14,15}};showarr2(stuff,ROWS);putchar('\n');times2(stuff,ROWS);showarr2(stuff,ROWS);return0;}voidtimes2(intar[][COLS],intr){introw,col;for(row=0;row<r;row++)for(col=0;col<COLS;col++)ar[row][col]*=2;}voidshowarr2(intar[][COLS],intr){introw,col;for(row=0;row<r;row++){for(col=0;col<COLS;col++)printf("%d",ar[row][col]);putchar('\n');}}PE 10--‐14/*ProgrammingExercise10-14*/#include<stdio.h>#defineROWS3#defineCOLS5voidstore(doublear[],intn);doubleaverage2d(introws,intcols,doublear[rows][cols]);doublemax2d(introws,intcols,doublear[rows][cols]);voidshowarr2(introws,intcols,doublear[rows][cols]);doubleaverage(constdoublear[],intn);intmain(void){doublestuff[ROWS][COLS];introw;for(row=0;row<ROWS;row++){printf("Enter%dnumbersforrow%d\n",COLS,row+1);store(stuff[row],COLS);}printf("arraycontents:\n");showarr2(ROWS,COLS,stuff);for(row=0;row<ROWS;row++)printf("averagevalueofrow%d=%g\n",row+1,average(stuff[row],COLS));printf("averagev alueofallrows=%g\n",average2d(ROWS,COLS,stuff));printf("largestvalue=%g\n",max2d(R OWS,COLS,stuff));printf("Bye!\n");return0;}voidstore(doublear[],intn){inti;for(i=0;i<n;i++){printf("Entervalue#%d:",i+1);scanf("%lf",&ar[i]);}}doubleaverage2d(introws,intcols,doublear[rows][cols]) {intr,c;doublesum=0.0;for(r=0;r<rows;r++)for(c=0;c<cols;c++)sum+=ar[r][c];if(rows*cols>0)returnsum/(rows*cols);elsereturn0.0;}doublemax2d(introws,intcols,doublear[rows][cols]) {intr,c;doublemax=ar[0][0];for(r=0;r<rows;r++)for(c=0;c<cols;c++)if(max<ar[r][c])max=ar[r][c];returnmax;}voidshowarr2(introws,intcols,doublear[rows][cols]) {introw,col;for(row=0;row<rows;row++){for(col=0;col<cols;col++)printf("%g",ar[row][col]);putchar('\n');}}doubleaverage(constdoublear[],intn){inti;doublesum=0.0;for(i=0;i<n;i++)sum+=ar[i];if(n>0)returnsum/n;elsereturn0.0;}Chapter 11 Programming ExercisesPE 11--‐1/*ProgrammingExercise11-1*/#include<stdio.h>#defineLEN10char*getnchar(char*str,intn);intmain(void){charinput[LEN];char*check;check=getnchar(input,LEN-1);if(check==NULL)puts("Inputfailed.");elseputs(input);puts("Done.\n");return0;}。
Chapter 2 Programming ExercisesPE 2--‐1/* Programming Exercise 2-1 */#include<stdio.h> intmain(void){ printf("GustavMahler\n");printf("Gustav\nMahler\n"); printf("Gustav");printf("Mahler\n");return 0;}PE 2--‐3/* Programming Exercise 2-3 */#include<stdio.h> intmain(void){ int ageyears; /* age inyears */ 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<stdio.h>voidjolly(void);voiddeny(void);int main(void){ jolly();jolly();jolly();deny();return0; }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<stdio.h> intmain(void){ inttoes;toes =10;printf("toes = %d\n", toes);printf("Twice toes = %d\n", 2 * toes); printf("toes squared = %d\n", 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<stdio.h>voidone_three(void); voidtwo(void); intmain(void){printf("startingnow:\n");one_three();printf("done!\n");return 0;}void one_three(void){printf("one\n");two();printf("three\n");}void two(void){printf("two\n");}Chapter 3 Programming ExercisesPE 3--‐2/* Programming Exercise 3-2 */#include<stdio.h> intmain(void){intascii;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<stdio.h> intmain(void){ float num;printf("Enter a floating-point value: ");scanf("%f", &num);printf("fixed-point notation: %f\n",num); printf("exponentialnotation: %e\n", num); printf("pnotation: %a\n", num); return 0;}PE 3--‐6/* Programming Exercise 3-6 */#include<stdio.h> intmain(void){float mass_mol = 3.0e-23; /* mass of water moleculein grams */ float mass_qt = 950; /* mass of quartof water in grams */ float quarts; float molecules;printf("Enter the number of quarts of water: ");scanf("%f", &quarts);molecules = quarts * mass_qt / mass_mol;printf("%f quarts of water contain %e molecules.\n", quarts, molecules); return 0;}Chapter 4 Programming ExercisesPE 4--‐1/* Programming Exercise 4-1 */#include<stdio.h> intmain(void){ charfname[40];charlname[40];printf("Enter your firstname: "); scanf("%s",fname); printf("Enter yourlast name: "); scanf("%s",lname); printf("%s, %s\n",lname, fname); return 0;}PE 4--‐4/* Programming Exercise 4-4 */#include<stdio.h> intmain(void){ floatheight;charname[40];printf("Enter your height ininches: "); scanf("%f", &height);printf("Enter your name: ");scanf("%s", name);printf("%s, you are %.3f feet tall\n", name, height / 12.0); return0;}PE 4--‐7/* Programming Exercise 4-7 */#include<stdio.h>#include<float.h> intmain(void){ float ot_f = 1.0 /3.0; double ot_d= 1.0 / 3.0;printf(" float values:");printf("%.4f %.12f %.16f\n", ot_f, ot_f, ot_f); printf("double values: ");printf("%.4f %.12f %.16f\n", ot_d,ot_d, ot_d); printf("FLT_DIG: %d\n",FLT_DIG); printf("DBL_DIG: %d\n",DBL_DIG); return 0;}Chapter 5 Programming Exercises PE 5--‐1/* Programming Exercise 5-1 */#include<stdio.h> intmain(void){ const intminperhour = 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 minutes\n", minutes, hours, mins); printf("Enter next minutes value (0 to quit): "); scanf("%d", &minutes);}printf("Bye\n");return0;}PE 5--‐3/* Programming Exercise 5-3 */#include<stdio.h> intmain(void){ const intdaysperweek = 7;int days, weeks,day_rem;printf("Enter the number ofdays: "); scanf("%d", &days);while (days > 0){ weeks = days /daysperweek; day_rem= days % daysperweek;printf("%d days are %d weeks and %ddays.\n", days, weeks, day_rem);printf("Enter the number of days (0 or less to end): "); scanf("%d", &days);}printf("Done!\n");return 0;}PE 5--‐5/* Programming Exercise 5-5*/ #include <stdio.h>int main(void) /* finds sum of first n integers */{int count,sum;int n;printf("Enter the upperlimit: "); scanf("%d", &n);count = 0; sum= 0; while(count++ < n) sum =sum + count; printf("sum= %d\n", sum); return 0;}PE 5--‐7/* ProgrammingExercise 5-7 */#include <stdio.h>voidshowCube(double x);int main(void) /* finds cube of entered number */ { double val;printf("Enter a floating-pointvalue: "); scanf("%lf", &val);showCube(val); return 0; }void showCube(double x){printf("The cube of %e is %e.\n", x, x*x*x );}Chapter 6 Programming ExercisesPE 6--‐1/* pe6-1.c *//* this implementation assumes the character codes */ /* are sequential, as they are in ASCII. */#include <stdio.h>#define SIZE 26 intmain( void ) { charlcase[SIZE]; int i;for (i = 0; i < SIZE;i++) lcase[i] = 'a'+ i; for (i = 0; i <SIZE; i++)printf("%c", lcase[i]);printf("\n");return 0;}PE 6--‐3/* pe6-3.c *//* this implementation assumes the character codes */ /* are sequential, as they are in ASCII. */#include<stdio.h> intmain( void ){ char let= 'F'; charstart; charend;for (end = let; end >= 'A'; end--){for (start = let; start >= end; start--) printf("%c", start);printf("\n");}return0;}PE 6--‐6/* pe6-6.c */#include<stdio.h> intmain( void ){ int lower, upper,index; int square,cube;printf("Enter startinginteger: "); scanf("%d",&lower); printf("Enterending integer: ");scanf("%d", &upper);printf("%5s %10s %15s\n", "num","square", "cube"); for (index = lower;index <= upper; index++){ square =index * index;cube = index * square;printf("%5d %10d %15d\n", index, square, cube);}return0;}PE 6--‐8/* pe6-8.c */#include<stdio.h> intmain( void ){ double n, m;doubleres;printf("Enter a pair of numbers: ");while (scanf("%lf %lf", &n, &m) == 2){res = (n - m) / (n * m);printf("(%.3g - %.3g)/(%.3g*%.3g) = %.5g\n", n, m, n, m, res); printf("Enter next pair (non-numeric to quit): "); }return 0;}PE 6--‐11/* pe6-11.c */#include<stdio.h>#defineSIZE 8 intmain( void ){ intvals[SIZE];int i;printf("Please enter %d integers.\n",SIZE); for (i = 0; i < SIZE; i++)scanf("%d", &vals[i]);printf("Here, in reverse order, are the values you entered:\n"); for (i = SIZE - 1; i >= 0; i--)printf("%d ", vals[i]); printf("\n"); return 0;}PE 6--‐13/* pe6-13.c *//* This version starts with the 0 power */#include<stdio.h>#defineSIZE 8 intmain( void ){inttwopows[SIZE];int i;int value = 1; /* 2 to the 0 */for (i = 0; i < SIZE; i++){ twopows[i]= value; value*= 2;}i =0;do{printf("%d ",twopows[i]); i++; } while (i < SIZE);printf("\n"); return 0;}PE 6--‐14/* pe-14.c *//* Programming Exercise 6-14 */ #include<stdio.h>#defineSIZE 8 intmain(void){ doublearr[SIZE];doublearr_cumul[SIZE];int i;printf("Enter %d numbers:\n", SIZE);for (i = 0; i < SIZE; i++){printf("value #%d: ", i + 1); scanf("%lf", &arr[i]); /* or scanf("%lf", arr + i);*/}arr_cumul[0] = arr[0]; /* set first element */ for (i = 1; i < SIZE; i++)arr_cumul[i] = arr_cumul[i-1] + arr[i];for (i = 0; i < SIZE;i++) printf("%8g ",arr[i]); printf("\n"); for(i = 0; i < SIZE; i++)printf("%8g ", arr_cumul[i]);printf("\n");return 0;}PE 6--‐16/* pe6-16.c */#include <stdio.h>#define RATE_SIMP 0.10#defineRATE_COMP0.05 #defineINIT_AMT 100.0int main( void ){double daphne =INIT_AMT;double deidre =INIT_AMT; intyears = 0;while (deidre <= daphne){ daphne +=RATE_SIMP * INIT_AMT;deidre += RATE_COMP *deidre;++years;}printf("Investment values after %d years:\n",years); printf("Daphne: $%.2f\n", daphne);printf("Deidre: $%.2f\n", deidre); return 0;}Chapter 7 Programming ExercisesPE 7--‐1/* ProgrammingExercise 7-1 */#include <stdio.h> intmain(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++; elseother++;}printf("spaces: %d, newlines: %d, others: %d\n", sp_ct, nl_ct, other); return0;}PE 7--‐3/* Programming Exercise 7-3 */#include<stdio.h> intmain(void){ int n;double sumeven =0.0; int ct_even= 0; doublesumodd = 0.0;int ct_odd = 0;while (scanf("%d", &n) == 1 && n != 0) {if (n % 2 == 0){sumeven += n;++ct_even;}else // n % 2 is either 1 or -1{sumodd += n;++ct_odd;} }printf("Number of evens: %d",ct_even); if (ct_even > 0)printf(" average: %g", sumeven /ct_even); putchar('\n');printf("Number of odds: %d",ct_odd); if (ct_odd > 0)printf(" average: %g", sumodd /ct_odd); putchar('\n');printf("\ndone\n");return0;}PE 7--‐5/* Programming Exercise 7-5 */#include<stdio.h> intmain(void){ charch; intct1 = 0;int ct2 = 0;while ((ch=getchar())!= '#'){switch(ch){case '.' : 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); return0;}PE 7--‐7// Programming Exercise 7-7#include <stdio.h>#define BASEPAY 10 // $10 per hour#define BASEHRS 40 // hours at basepay#define OVERTIME 1.5 // 1.5 time#define AMT1 300 // 1st rate tier#define AMT2 150 // 2st rate tier#define RATE1 0.15 // rate for 1st tier#define RATE2 0.20 // rate for 2ndtier #define RATE3 0.25 // rate for3rd tier int main(void){doublehours;double gross;double net;double taxes;printf("Enter the number of hours worked thisweek: "); scanf("%lf", &hours); if (hours<= BASEHRS) gross = hours * BASEPAY;elsegross = BASEHRS * BASEPAY + (hours - BASEHRS) * BASEPAY * OVERTIME; if (gross <= AMT1) taxes = gross * RATE1; else if (gross <= AMT1 + AMT2)taxes = AMT1 * RATE1 + (gross - AMT1)* RATE2; elsetaxes = AMT1 * RATE1 + AMT2 * RATE2 + (gross - AMT1- AMT2) * RATE3; net = gross - taxes;printf("gross: $%.2f; taxes: $%.2f; net: $%.2f\n", gross, taxes, net); return0;}PE 7--‐9/* Programming Exercise 7-9 */#include<stdio.h>#include<stdbool.h> intmain(void){intlimit;int num;int div;bool numIsPrime; // use int if stdbool.h not availableprintf("Enter a positive integer: ");while (scanf("%d", &limit) == 1 &&limit > 0){if (limit > 1)printf("Here are the prime numbers up through %d\n", limit); elseprintf("No primes.\n");for (num = 2; num <= limit;num++){for (div = 2, numIsPrime = true; (div * div) <= num; div++) if (num % div == 0) numIsPrime = false; if (numIsPrime)printf("%d is prime.\n", num);}printf("Enter a positive integer (q to quit): ");}printf("Done!\n");return 0;}PE 7--‐11/* pe7-11.c *//* Programming Exercise 7-11 */#include<stdio.h>#include<ctype.h> intmain(void){const doubleprice_artichokes = 2.05;const double price_beets =1.15; const doubleprice_carrots = 1.09; constdouble DISCOUNT_RATE =0.05; const double under5 =6.50; const double under20 =14.00; const double base20 =14.00; const double extralb =0.50;charch;doublelb_artichokes = 0;double lb_beets = 0;double lb_carrots =0; double lb_temp;double lb_total;doublecost_artichokes;double cost_beets;doublecost_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 != 'Q') { if (ch == '\n')continue; while(getchar() != '\n')continue; ch =tolower(ch); switch(ch) {case 'a' : printf("Enter pounds of artichokes: "); scanf("%lf", &lb_temp); lb_artichokes += lb_temp; break;case 'b' : printf("Enter pounds of 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 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 + lb_beets + lb_carrots; if(lb_total <= 0) shipping = 0.0; else if(lb_total < 5.0) shipping = under5; else if(lb_total < 20) shipping = under20; elseshipping = base20 + extralb *lb_total; if (cost_total > 100.0)discount = DISCOUNT_RATE* cost_total; else discount =0.0;final_total = cost_total + shipping - discount; printf("Your order:\n");printf("%.2f lbs of artichokes at $%.2f per pound:$ %.2f\n", lb_artichokes,price_artichokes, cost_artichokes); printf("%.2flbs of beets at $%.2f per pound: $%.2f\n",lb_beets, price_beets, cost_beets); printf("%.2flbs of carrots at $%.2f per pound: $%.2f\n",lb_carrots, price_carrots, cost_carrots);printf("Total cost of vegetables: $%.2f\n",cost_total); if (cost_total > 100)printf("V olume discount: $%.2f\n", discount); printf("Shipping: $%.2f\n", shipping); printf("Total charges:$%.2f\n", final_total); return 0; }Chapter 8 Programming ExercisesPE 8--‐1/* Programming Exercise 8-1 */#include <stdio.h>int main(void) { int ch;int ct = 0; while ((ch= getchar()) != EOF)ct++;printf("%d characters read\n", ct);return0;}PE 8--‐3/* Programming Exercise 8-3 *//* Using ctype.h eliminates need to assume consecutive coding */#include <stdio.h>#include<ctype.h> intmain(void) { intch; unsignedlong uct = 0;unsigned long lct= 0; unsignedlong oct = 0;while ((ch =getchar()) != EOF) if(isupper(ch)) uct++;else if (islower(ch))lct++; elseoct++;printf("%lu uppercase characters read\n", uct);printf("%lu lowercase characters read\n", lct);printf("%lu other characters read\n", oct);return0;}/* or you could useif (ch >= 'A' && ch<= 'Z') uct++;else if (ch >= 'a' && ch<= 'z') lct++; elseoct++;*/PE 8--‐5/* Programming Exercise 8-5 *//* binaryguess.c -- an improved number-guesser *//* but relies upon truthful, correct responses */#include <stdio.h>#include <ctype.h> intmain(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("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 != 'h' && response != 'l'){printf("I don't understand that response. Please enter h for\n"); 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 + low) /2;printf("Well, then, is it %d?\n", guess);}printf("I knew I could do it!\n");return 0;}PE 8--‐7/* Programming Exercise 8-7 */#include <stdio.h>#include <ctype.h>#include <stdio.h>#define BASEPAY1 8.75 // $8.75 per hour#define BASEPAY2 9.33 // $9.33 per hour#define BASEPAY3 10.00 // $10.00 per hour#define BASEPAY4 11.20 // $11.20 per hour#define BASEHRS 40 // hours at basepay#define OVERTIME 1.5 // 1.5 time#define AMT1 300 // 1st rate tier#define AMT2 150 // 2st rate tier#define RATE1 0.15 // rate for 1st tier#define RATE2 0.20 // rate for2nd tier #define RATE3 0.25 //rate for 3rd tier int getfirst(void); voidmenu(void); int main(void){ doublehours;doublegross;double net;doubletaxes;double pay;charresponse;menu();while ((response = getfirst()) != 'q'){if (response == '\n') /* skip over newlines */ continue;response = tolower(response); /* accept A as a, etc. */ switch (response){case 'a': pay = BASEPAY1;break; case 'b': pay =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; // go to beginning of loop}printf("Enter the number of hours worked thisweek: "); scanf("%lf", &hours); if(hours <= BASEHRS) gross = hours * pay;elsegross = BASEHRS * pay + (hours - BASEHRS) *pay * OVERTIME; if (gross <= AMT1) taxes= gross * RATE1; else if (gross <= AMT1 + AMT2)taxes = AMT1 * RATE1 + (gross - AMT1) *RATE2; elsetaxes = AMT1 * RATE1 + AMT2 * RATE2 + (gross - AMT1 - AMT2) * RATE3; net = gross - taxes;printf("gross: $%.2f; taxes: $%.2f; net: $%.2f\n", gross, taxes, net); menu(); }printf("Done.\n");return0;}void menu(void){printf("********************************************************""*********\n");printf("Enter the letter corresponding to the desired payrate"" or action:\n");printf("a) $%4.2f/hr b) $%4.2f/hr\n",BASEPAY1, BASEPAY2);printf("c) $%5.2f/hr d) $%5.2f/hr\n",BASEPAY3, BASEPAY4); printf("q)quit\n");printf("********************************************************""*********\n");}int getfirst(void){intch;ch = getchar();while (isspace(ch))ch = getchar();while (getchar() !='\n') continue;return ch;}Chapter 9 Programming Exercises PE 9--‐1/* Programming Exercise 9-1 */#include <stdio.h>double min(double,double); int main(void){double x, y; printf("Entertwo numbers (q to quit): "); while(scanf("%lf %lf", &x, &y) == 2){ printf("The smaller numberis %f.\n", min(x,y)); printf("Next two values (q to quit): ");}printf("Bye!\n");return0;}double min(double a, double b){return a < b ? a : b;}/* alternativeimplementation doublemin(double a, double b){ if (a <b)return a;elsereturn b;}*/PE 9--‐3/* Programming Exercise 9-3 */#include <stdio.h>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()) != '#'){ 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");return0;}// start rows and cols at 0void chLineRow(char ch, intc, int r){int col, row;for (row = 0; row < r ; row++){for (col = 0; col < c;col++) putchar(ch);putchar('\n');}return;}PE 9--‐5/* Programming Exercise 9-5 */#include <stdio.h>void larger_of(double *p1, double*p2); int main(void){double x, y; printf("Entertwo numbers (q to quit): "); while(scanf("%lf %lf", &x, &y) == 2){larger_of(&x, &y);printf("The modified values are %f and %f.\n", x, y); printf("Next two values (q to quit): ");}printf("Bye!\n");return0;}void larger_of(double *p1, double *p2){ if(*p1 > *p2)*p2 = *p1;else*p1 = *p2;}// alternatively:/*void larger_of(double *p1, double *p2){*p1= *p2 = *p1 > *p2 ? *p1 : *p2;}*/PE 9--‐8/* Programming Exercise 9-8*/ #include <stdio.h>double power(double a, int b); /* ANSIprototype */ int main(void) { double x, xpow;int n; printf("Enter a number and the integer power"); printf(" to which\nthe number willbe raised. Enter q"); printf(" to quit.\n");while (scanf("%lf%d", &x, &n) == 2){ xpow = power(x,n); /* function call*/ printf("%.3g to the power %d is %.5g\n", x,n, xpow); printf("Enter next pair of numbersor q to quit.\n");} printf("Hope you enjoyed this powertrip -- bye!\n"); return 0;} double power(double a, int b) /* function definition */{ doublepow = 1;int i; if(b == 0){ if (a== 0)printf("0 to the 0 undefined; using 1 as the value\n"); pow = 1.0; } else if (a == 0) pow = 0.0; else if (b > 0) for(i = 1; i <= b; i++) pow *= a; else /* b < 0 */ pow = 1.0 / power(a, - b);return pow; /* return the value of pow */}PE 9--‐10/* Programming Exercise 9-10 */#include <stdio.h> voidto_base_n(int x, int base); intmain(void) { int number; int b;int count; printf("Enter aninteger (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("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"); return 0;}void to_base_n(int x, int base) /* recursive function */ { int r; r = x % base;if (x >= base)to_base_n(x / base,base); putchar('0' + r);return;}Chapter 10 Programming ExercisesPE 10--‐1/* Programming Exercise 10-1 */#include <stdio.h>#define MONTHS 12 // number ofmonths in a year #define YRS 5 //number of years of data int main(void){// initializing rainfall data for 2010 - 2014const float rain[YRS][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; floatsubtot, total;printf(" YEAR RAINFALL(inches)\n"); for (year = 0, total = 0;year < YRS; year++){ /* for each year, sum rainfall for eachmonth */ for (month = 0, subtot = 0; month < MONTHS; month++) subtot += *(*(rain +year) + month); printf("%5d %15.1f\n", 2010 + year, subtot);total += subtot; /* total for all years */}printf("\nThe yearly average is %.1f inches.\n\n",total/YRS); printf("MONTHLY A VERAGES:\n\n");printf(" Jan Feb Mar Apr May Jun Jul Aug Sep Oct "); printf(" Nov Dec\n");for (month = 0; month < MONTHS; month++){ /* for each month, sum rainfall overyears */ for (year = 0, subtot =0; year < YRS;year++) subtot += *(*(rain + year) + month); printf("%4.1f ", subtot/YRS);}printf("\n");return 0;}PE 10--‐3/* Programming Exercise 10-3 */#include <stdio.h>#define LEN 10int max_arr(const int ar[],int n); void show_arr(constint ar[], int n);int main(void){int orig[LEN] ={1,2,3,4,12,6,7,8,9,10}; int max;show_arr(orig, LEN);max = max_arr(orig, LEN);printf("%d = largest value\n",max);return0;}int max_arr(const int ar[], int n){ int i;int max =ar[0];/* don't use 0 as initial max value -- fails if all array values are neg */ for (i = 1; i < n;i++) if (max <ar[i]) max =ar[i]; return max;}void show_arr(const int ar[], int n){ int i; for (i= 0; i < n; i++)printf("%d ", ar[i]);putchar('\n');}。
第二章:开始学习C++//ex2.1--display your name and address#include<iostream>int main(void){using namespace std;cout<<"My name is liao chunguang and I live in hunan chenzhou.\n”;}//ex2.2--convert the furlong units to yard uints-把浪单位换位码单位#include<iostream>double fur2yd(double);int main(){using namespace std;cout<<"enter the distance measured by furlong units:";double fur;cin>>fur;cout<<"convert the furlong to yard"<<endl;double yd;yd=fur2yd(fur);cout<<fur<<" furlong is "<<yd<<" yard"<<endl;return 0;}double fur2yd(double t){return 220*t;}//ex2.3-每个函数都被调用两次#include<iostream>void mice();void see();using namespace std;int main(){mice();mice();see();see();return 0;}void mice(){cout<<"three blind mice"<<endl;}void see(){cout<<"see how they run"<<endl;}//ex2.4#include<iostream>int main(){using namespace std;cout<<"Enter your age:";int age;cin>>age;int month;month=age*12;cout<<age<<" years is "<<month<<" months"<<endl;return 0;}//ex2.5---convert the Celsius valve to Fahrenheit value#include<iostream>double C2F(double);int main(){using namespace std;cout<<"please enter a Celsius value:";double C;cin>>C;double F;F=C2F(C);cout<<C<<" degrees Celsius is "<<F<<" degrees Fahrenheit."<<endl;return 0;}double C2F(double t){return 1.8*t+32;}//ex2.6---convert the light years valve to astronomical units--把光年转换为天文单位#include<iostream>double convert(double);//函数原型int main(){using namespace std;cout<<"Enter the number of light years:";double light_years;cin>>light_years;double astro_units;astro_units=convert(light_years);cout<<light_years<<" light_years = "<<astro_units<<" astronomical units."<<endl; return 0;}double convert(double t){return 63240*t;//1 光年=63240 天文单位}//ex2.7--显示用户输入的小时数和分钟数#include<iostream>void show();main(){using namespace std;show();return 0;}void show(){using namespace std;int h,m;cout<<"enter the number of hours:";cin>>h;cout<<"enter the number of minutes:";cin>>m;cout<<"Time:"<<h<<":"<<m<<endl;}第三章:处理数据//ex3.1—将身高用英尺(feet)和英寸(inch)表示#include<iostream>const int inch_per_feet=12;// const 常量--1feet=12inches--1 英尺=12 英寸int main(){using namespace std;cout<<"please enter your height in inches:___\b\b\b";// \b 表示为退格字符int ht_inch;cin>>ht_inch;int ht_feet=ht_inch/inch_per_feet;//取商int rm_inch=ht_inch%inch_per_feet;//取余cout<<"your height is "<<ht_feet<<" feet,and "<<rm_inch<<" inches\n";return 0;}//ex3.2--计算相应的body mass index〔体重指数〕#include<iostream>const int inch_per_feet=12;const double meter_per_inch=0.0254;const double pound_per_kilogram=2.2;int main(){using namespace std;cout<<"Please enter your height:"<<endl;cout<<"First,enter your height of feet part〔输入你身高的英尺部分〕:_\b"; int ht_feet;cin>>ht_feet;cout<<"Second,enter your height of inch part〔输入你身高的英寸部分〕:_\b"; int ht_inch;cin>>ht_inch;cout<<"Now,please enter your weight in pound:___\b\b\b";double wt_pound;cin>>wt_pound;int inch;inch=ht_feet*inch_per_feet+ht_inch;double ht_meter;ht_meter=inch*meter_per_inch;double wt_kilogram;wt_kilogram=wt_pound/pound_per_kilogram;cout<<endl;cout<<"Your pensonal body information as follows:"<<endl;cout<<"身高:"<<inch<<"(英尺inch)\n"<<"身高:"<<ht_meter<<"(米meter)\n"<<"体重:"<<wt_kilogram<<"(千克kilogram)\n";double BMI;BMI=wt_kilogram/(ht_meter*ht_meter);cout<<"your Body Mass Index(体重指数) is "<<BMI<<endl;return 0;}//ex3.3 以度,分,秒输入,以度输出#include<iostream>const int minutes_per_degree=60;const int seconds_per_minute=60;int main(){using namespace std;cout<<"Enter a latitude in degrees,minutes,and seconds:\n";cout<<"First,enter the degrees:";int degree;cin>>degree;cout<<"Next,enter the minutes of arc:";int minute;cin>>minute;cout<<"Fianlly,enter the seconds of arc:";int second;cin>>second;double show_in_degree;show_in_degree=(double)degree+(double)minute/minutes_per_degree+(double)second/mi nutes_per_degree/seconds_per_minute;cout<<degree<<" degrees,"<<minute<<" minutes,"<<second<<"seconds="<<show_in_degree<<" degrees\n";return 0;}//ex3.4#include<iostream>const int hours_per_day=24;const int minutes_per_hour=60;const int seconds_per_minute=60;int main(){using namespace std;cout<<"Enter the number of seconds:";long seconds;cin>>seconds;int Day,Hour,Minute,Second;Day=seconds/seconds_per_minute/minutes_per_hour/hours_per_day;Hour=seconds/seconds_per_minute/minutes_per_hour%hours_per_day;Minute=seconds/seconds_per_minute%minutes_per_hour;Second=seconds%seconds_per_minute;cout<<seconds<<"seconds = "<<Day<<" days,"<<Hour<<" hours,"<<Minute<<" minutes,"<<Second<<" seconds\n";return 0;}//ex3.5#include<iostream>int main(){using namespace std;cout<<"Enter the world population:";long long world_population;cin>>world_population;cout<<"Enter the population of the US:";long long US_population;cin>>US_population;double percentage;percentage=(double)US_population/world_population*100;cout<<"The population of the US is "<<percentage<<"% of the world population.\n"; return 0;}//ex3.6 汽车耗油量-美国(mpg)or 欧洲风格(L/100Km)#include<iostream>int main(){using namespace std;cout<<"Enter the miles of distance you have driven:";double m_distance;cin>>m_distance;cout<<"Enter the gallons of gasoline you have used:";double m_gasoline;cin>>m_gasoline;cout<<"Your car can run "<<m_distance/m_gasoline<<" miles per gallon\n";cout<<"Computing by European style:\n";cout<<"Enter the distance in kilometers:";double k_distance;cin>>k_distance;cout<<"Enter the petrol in liters:";double k_gasoline;cin>>k_gasoline;cout<<"In European style:"<<"your can used "<<100*k_gasoline/k_distance<<" liters of petrol per 100 kilometers\n";return 0;}//ex3.7 automobile gasoline consumption-耗油量--欧洲风格(L/100Km)转换成美国风格(mpg) #include<iostream>int main(){using namespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"European style(liters per 100 kilometers):";double Euro_style;cin>>Euro_style;cout<<"Converts to U.S. style(miles per gallon):"<<endl;cout<<Euro_style<<" L/100Km = "<<62.14*3.875/Euro_style<<" mpg\n";return 0;}// Note that 100 kilometers is 62.14 miles, and 1 gallon is 3.875 liters.//Thus, 19 mpg is about 12.4 L/100Km, and 27 mpg is about 8.7 L/100Km.Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):12.4Converts to U.S. style(miles per gallon):12.4 L/100Km = 19.4187 mpgPress any key to continue// ex3.7 automobile gasoline consumption-耗油量--美国风格(mpg)转换成欧洲风格(L/100Km)#include<iostream>int main(){using namespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"U.S. style(miles per gallon):";double US_style;cin>>US_style;cout<<"Converts to European style(miles per gallon):"<<endl;cout<<US_style<<" mpg = "<< 62.14*3.875/US_style<<"L/100Km\n";return 0;}// Enter the automobile gasoline consumption figure inU.S. style(miles per gallon):19Converts to European style(miles per gallon):19 mpg = 12.6733L/100KmPress any key to continue第四章复合类型//ex4.1 display the information of student#include<iostream>const int Asize=20;using namespace std;struct student//定义结构描述{char firstname[Asize];char lastname[Asize];char grade;int age;};void display(student);//函数原型放在结构描述后int main(){cout<<"what is your first name?"<<endl;student lcg;//创建结构变量〔结构数据对象〕cin.getline(lcg.firstname,Asize);cout<<"what is your last name?"<<endl;cin.getline(stname,Asize);cout<<"what letter grade do you deserve?"<<endl;cin>>lcg.grade;cout<<"what is your age?"<<endl;cin>>lcg.age;display(lcg);return 0;}void display(student name){cout<<"Name: "<<name.firstname<<","<<stname<<endl;cout<<"Grade:"<<char(name.grade+1)<<endl;cout<<"Age:"<<name.age<<endl;}//ex4.2 use the string-class instead of char-array#include<iostream>#include<string>int main(){using namespace std;string name,dessert;cout<<"Enter your name: \n";getline(cin,name);cout<<"Enter your favorite dessert: \n";getline(cin,dessert);cout<<"I have some delicious "<<dessert;cout<<" for you, "<<name<<".\n";return 0;}//有时候会遇到需要按下两次回车键才能正确的显示结果,这是vc++6.0 的一个BUG,更改如下:else if (_Tr::eq((_E)_C, _D)){_Chg = true;_I.rdbuf()->sbumpc();//修改后的break; }ex4.3 输入其名和姓,并组合显示#include<iostream>#include<cstring>const int Asize=20;int main(){using namespace std;char fname[Asize];char lname[Asize];char fullname[2*Asize+1];cout<<"Enter your first name:";//输入名字,存储在fname[]数组中cin.getline(fname,Asize);cout<<"Enter your last name:";//输入姓,存储在lname[]数组中cin.getline(lname,Asize);strncpy(fullname,lname,Asize);//把姓lname 复制到fullname 空数组中strcat(fullname,", ");//把“,”附加到上述fullname 尾部strncat(fullname,fname,Asize);//把fname 名字附加到上述fullname 尾部fullname[2*Asize]='\0';//为防止字符型数组溢出,在数组结尾添加结束符cout<<"Here's the information in a single string:"<<fullname<<endl;//显示组合结果return 0;}#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <cstring>const int Asize = 20;int main(){using namespace std;char firstname[Asize];char lastname[50];cout << "Enter your first name: ";cin.getline(firstname,Asize);cout << "Enter your last name: ";cin.getline(lastname,50);strcat(lastname,", ");strncat(lastname,firstname,Asize);cout << "Here's the information in a single string: "<< lastname <<endl;return 0;}//ex4.4 使用string 对象存储、显示组合结果#include<iostream>#include<string>int main(){using namespace std;string fname,lname,attach,fullname;cout<<"Enter your first name:";getline(cin,fname);//note:将一行输入读取到string 类对象中使用的是getline(cin,str) //它没有使用句点表示法,所以不是类方法cout<<"Enter your last name:";getline(cin,lname);attach=", ";fullname=lname+attach+fname;cout<<"Here's the information in a single string:"<<fullname<<endl;return 0;}//ex4.5 declare a struct and initialize it 声明结果并创建一个变量#include<iostream>const int Asize=20;struct CandyBar{char brand[Asize];double weight;int calory;};int main(){using namespace std;CandyBar snack={"Mocha Munch",2.3,350};cout<<"Here's the information of snack:\n";cout<<"brand:"<<snack.brand<<endl;cout<<"weight:"<<snack.weight<<endl;cout<<"calory:"<<snack.calory<<endl;return 0;}//ex4.6 结构数组的声明及初始化#include<iostream>const int Asize=20;struct CandyBar{char brand[Asize];double weight;int calory;};int main(){using namespace std;CandyBar snack[3]={{"Mocha Munch",2.3,350},{"XuFuJi",1.1,300},{"Alps",0.4,100}};for(int i=0;i<3;i++)//利用for 循环来显示snack 变量的内容{cout<<snack[i].brand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;}return 0;}//ex4.7 pizza 披萨饼#include<iostream>#include<string>const int Size=20;struct pizza//声明结构{char company[Size];double diameter;double weight;};int main(){using namespace std;pizza pie;//创建一个名为pie 的结构变量cout<<"What's the name of pizza company:";cin.getline(pie pany,Size);cout<<"What's the diameter of pizza:";cin>>pie.diameter;cout<<"What's the weight of pizza:";cin>>pie.weight;cout<<"company:"<<pie pany<<endl;cout<<"diameter:"<<pie.diameter<<"inches"<<endl;cout<<"weight:"<<pie.weight<<"ounches"<<endl;return 0;}//ex4.8 pizza pie 披萨饼使用new 创建动态结构#include<iostream>#include<string>const int Size=20;struct pizza//声明结构{char company[Size];double diameter;double weight;};int main(){using namespace std;pizza *pie=new pizza;//使用new 创建动态结构cout<<"What's the diameter of pizza:";cin>>pie->diameter;cin.get();//读取下一个字符cout<<"What's the name of pizza company:";cin.get(pie->company,Size);cout<<"What's the weight of pizza:";cin>>pie->weight;cout<<"diameter:"<<pie->diameter<<" inches"<<endl;cout<<"company:"<<pie->company<<endl;cout<<"weight:"<<pie->weight<<" ounches"<<endl;delete pie;//delete 释放内存return 0;}//ex.4.9 使用new 动态分配数组—方法1#include<iostream>#include<string>using namespace std;struct CandyBar{string brand;double weight;int calory;};int main(){CandyBar *snack= new CandyBar[3];snack[0].brand="A";//单个初始化由new 动态分配的内存snack[0].weight=1.1;snack[0].calory=200;snack[1].brand="B";snack[1].weight=2.2;snack[1].calory=400;snack[2].brand="C";snack[2].weight=4.4;snack[2].calory=500;for(int i=0;i<3;i++){cout << " brand: " << snack[i].brand << endl;cout << " weight: " << snack[i].weight << endl;cout << " calorie: " << snack[i].calory << endl<<endl;}delete [] snack;return 0;}//ex.4.10 数组—方法1#include <iostream>int main(){using namespace std;const int Size = 3;int success[Size];cout<<"Enter your success of the three times 40 meters running:\n"; cin >> success[0]>>success[1]>>success[2];cout<<"success1:"<<success[0]<<endl;cout<<"success2:"<<success[1]<<endl;cout<<"success3:"<<success[2]<<endl;double average=(success[0]+success[1]+success[2])/3;cout<<"average:"<<average<<endl;return 0;}//ex.4.10 array—方法2#include <iostream>#include <array>int main(){using namespace std;array<double,4>ad={0};cout<<"Enter your success of the three times 40 meters running:\n"; cin >> ad[0]>>ad[1]>>ad[2];cout<<"success1:"<<ad[0]<<endl;cout<<"success2:"<<ad[1]<<endl;cout<<"success3:"<<ad[2]<<endl;ad[3]=(ad[0]+ad[1]+ad[2])/3;cout<<"average:"<<ad[3]<<endl;return 0;}第五章循环和关系表达式//ex.5.1#include <iostream>int main(){using namespace std;cout<<"Please enter two integers: ";int num1,num2;cin>>num1>>num2;int sum=0;for(int temp=num1;temp<=num2;++temp)//or temp++sum+=temp;cout<<"The sum from "<<num1<<" to "<<num2<<" is "<<sum<<endl; return 0;}//ex.5.2#include <iostream>#include<array>int main(){using namespace std;array<long double,101>ad={0};ad[1]=ad[0]=1L;for(int i=2;i<101;i++)ad[i]=i*ad[i-1];for(int i=0;i<101;i++)cout<<i<<"! = "<<ad[i]<<endl;return 0;}#include <iostream>#include <array>using namespace std;int main(){array<long double, 101> multiply;multiply[0] = multiply[1] = 1LL;for (int i = 2; i <= 100; i++)multiply[i] = multiply[i-1]*i;cout << multiply[100];return 0;}//ex.5.3#include <iostream>int main(){using namespace std;cout<<"Please enter an integer: ";int sum=0,num;while((cin>>num)&&num!=0){sum+=num;cout<<"So far, the sum is "<<sum<<endl;cout<<"Please enter an integer: ";}return 0;}//ex.5.4#include <iostream>int main(){using namespace std;double sum1,sum2;sum1=sum2=0.0;int year=0;while(sum2<=sum1){++year;sum1+=10;sum2=(100+sum2)*0.05+sum2;}cout<<"经过"<<year<<"年后,Cleo 的投资价值才能超过Daphne 的投资价值。
注意:下面的勘误中,红色字体为修改后的文字,提请各位读者注意。
第 6 页,” 1.6 语言标准”中的第 3 行,将 1987 年修改为 1978 年。
第 22 页,” 2. main ()函数”中的第 1 行, int main (void ) 后面的分号( ; )删除。
第 24 页,“5. 声明”的第 10 行,也就 是一个变量、函数或其他实体的名称。
第 27 页,图 2.3 中,下划线应该只包含括号中的内容;第 2 段的第 4 行,而不是存储 在 源代码 中的指令。
第 30页,“2.5.4 打印多个值”的第 4行,双引 号后面的第 1 个变量。
第 34页,“2.7.3 程序状态”第 2段的第 4 行,要尽量忠实 于代码来模拟。
第 35页,“2.10 本章小结”第 2段的第 1句,声明 语句为变量指定变量名, 并标识该变量中存 储的数据类型;本页倒数第 2 行,即 检查程序每执行一步后所有变量的值。
第37页,“2.12编程练习”中第1题,把你的名和姓打印在一行……把你的 名和姓分别打印在 两行……把你的 名和姓打印在一行……把示例的内容换成你的 名字。
第 40 页,第 1 行,用于把英 磅常衡盎司转换为… … 第44页,“3.4 C 语言基本数据类型”的第 1句,本节将 详细介绍C 语言的基本属性类型……第 46页,“5. 八进制和十六进制”的第 4句,十六进制数 3的二进制数 是 0011,十六进制数 5 的二进制数 是 0101;“6. 显示八进制和十六进制”的第 1 句,既可以使用 也可以 显示不同进制 的数;将“回忆一下……程序在执行完毕后不会立即关闭执行窗口”放到一个括号里。
第 47页,“2. 使用多种整数类型的原因”第 3句,过去的一台运行 Windows 3.x 的机器上。
第 53 页,图 3.5 下面的第 4 行“上面最后一个例子( printf ( “ ” a \\ is abackslash. ” \n ” ); )” 第 56页,正文的第 2行和第 4行应该分别为 printf ( “me32 = %““d”“\n ”, me32); printf ( “me32 = %d\n ” , me32);第 61 页,“无符号类型”的最后 1 句,相当于 unsigned int (即两者之间添加一个空格 )。
C Primer Plus第六版中文版习题答案Github: https:///zhayujie/C-Primer-PlusEmail: yjzha1996@第一章1.#include <stdio.h>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;}第二章3.#include<stdio.h>int main(void){int days,years=21;days=years*365;printf("我年龄是%d岁,%d天\n",years,days);return 0;}4.#include<stdio.h>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");}5.#include<stdio.h>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");}#include<stdio.h>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;}8.#include<stdio.h>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");}第三章2.#include<stdio.h>int main(void){char ch;printf("please input a number:");scanf("%d",&ch);printf("%c\n",ch);return 0;}4.#include<stdio.h>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;}5.#include<stdio.h>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;}7.#include<stdio.h>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;}8.#include<stdio.h>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;}第四章1.#include<stdio.h>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;}2.#include<stdio.h>#include<string.h>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;}4.#include<stdio.h>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;}5.#include<stdio.h>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;}6.#include<stdio.h>#include<string.h>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;}7.#include<stdio.h>#include<float.h>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;}8.#include<stdio.h>#define GALLON 3.758 //1 gallon=3.785 liters#define MILE 1.609 //1 mile=1.609 kilometersint 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;}第五章1.#include<stdio.h>#define H_P_M 60 //1h=60minint 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;}2.#include<stdio.h>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;}3.#include<stdio.h>#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;}4.#include<stdio.h>#define CM_PER_FEET 30.48 //1feet=30.48cm#define CM_PER_INCH 2.54 //1inch=2.54cmint 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;}5.#include<stdio.h>int main(void){int count,sum,days;printf("Input the number of days: ");scanf("%d",&days);count=sum=0;while(count++<days)sum=sum+count;printf("The money you earned: %d\n",sum);return 0;}6.#include<stdio.h>int main(void){int count,sum,days;printf("Input the number of days: ");scanf("%d",&days);count=sum=0;while(count++<days)sum=sum+count*count;printf("The money you earned: %d\n",sum);return 0;}7.#include<stdio.h>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);}8.#include<stdio.h>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");}9.#include<stdio.h>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);}第六章1.#include<stdio.h>#define SIZE 26int main(void){char ch[SIZE];int index;for(index=0;index<SIZE;index++){ch[index]='a'+index;printf("%c ",ch[index]);}printf("\n");return 0;}2.#include<stdio.h>int main(void){int i,j;for(i=1;i<=5;i++)for(j=1;j<=i;j++)printf("$");printf("\n");}return 0;}3.#include<stdio.h>int main(void){int i,j;for(i=1;i<=6;i++){for(j=0;j<i;j++)printf("%c",'F'-j); printf("\n");}return 0;}4.#include<stdio.h>#define ROWS 6int main(void){char ch;int i,j;for(ch='A',i=0;i<ROWS;i++) {for(j=0;j<=i;j++)printf("%c",ch++); printf("\n");}return 0;}5.#include<stdio.h>#define ROWS 5int main(void){char ch='A';int i,j;for(i=1;i<=ROWS;i++){for(j=1;j<=ROWS-i;j++)printf(" ");for(j=0;j<i;j++)printf("%c",ch+j);for(j=i-2;j>=0;j--)printf("%c",ch+j);printf("\n");}return 0;}6.#include<stdio.h>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;}7.//与题目不同打印的是句子#include<stdio.h>#include<string.h>#define SIZE 40int main(void){int i,index=-1;char ch[SIZE];printf("Input a word: ");do{ index++;scanf("%c",&ch[index]);}while(ch[index]!='\n');for(i=index+1;i<=40;i++)ch[i]='\0';for(index=strlen(ch);index>=0;index--)printf("%c",ch[index]);printf("\n");return 0;}8.#include<stdio.h>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;}9.#include<stdio.h>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)); //返回运算结果}10.#include <stdio.h>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;}11.#include <stdio.h>#define SIZE 8int main(void){int num[SIZE];int index;printf("Enter 8 integers: ");for (index=0; index<SIZE; index++) //输入8个整数scanf("%d", &num[index]);for (index=SIZE-1; index >= 0; index--) //倒序输出printf("%d ", num[index]);printf("\n");return 0;}12.#include <stdio.h>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;}13.#include <stdio.h>#define SIZE 8int 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的值doprintf("%d ", num[index++]);while (index < SIZE); //do while循环显示数组元素的值printf("\n");return 0;}14.#include <stdio.h>#define SIZE 8int 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;}15.#include <stdio.h>#include <string.h>#define SIZE 255int 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;}16.#include <stdio.h>#define RATE_DAPHNE 0.1#define RATE_DEIRDRE 0.05 //两人的利率#define MONEY 100int 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;}17.#include <stdio.h>#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;}18.#include <stdio.h>#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;}第七章1.#include <stdio.h>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++;elsen_others++;}printf("Spaces: %d, newlines: %d, others: %d\n", n_space, n_newline, n_others);return 0;}2.#include <stdio.h>#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;}3.#include <stdio.h>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;}4.#include <stdio.h>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;}5.#include <stdio.h>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;}6.#include <stdio.h>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;}7.#include <stdio.h>#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;elsegross = TIME * BASE + (hour - TIME) * MUL * BASE;//计算总收入if (gross <= BREAK1)tax = gross * RATE1;else if (gross <= BREAK2)tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2;elsetax = 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;8.#include <stdio.h>#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;elsegross = TIME * base + (hour - TIME) * MUL * base;//计算总收入if (gross <= BREAK1)tax = gross * RATE1;else if (gross <= BREAK2)tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2;elsetax = 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;}9.#include <stdio.h>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;}10.#include <stdio.h>#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;elsetax = tax_break * RATE1 + (income - tax_break) * RATE2; //计算税金printf("The tax is $%.2lf.\n", tax);printf("Your next input: \n");goto printpart; //回到输入阶段}return 0;}11.#include <stdio.h>#include <ctype.h>#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;}elseorder_cost = veg_cost; //折扣计算if (total_weight <= BREAK1)pack_tran_fee = FEE1;else if (total_weight <= BREAK2)pack_tran_fee = FEE2;elsepack_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:。
Chapter 2 Programming ExercisesPE 2—‐1/* Programming Exercise 2-1 */#include 〈stdio.h> int main(void){ printf("Gustav Mahler\n");printf(”Gustav\nMahler\n"); printf(”Gustav "); printf(”Mahler\n");return 0;}PE 2—。
‐3/* Programming Exercise 2-3 */#include 〈stdio.h〉 int main(void){ int ageyears; /* age in years */ intagedays; /* 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 <stdio.h> void jolly(void); void deny(void); intmain(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 <stdio.h〉 int main(void){ int toes; toes =10;printf(”toes = %d\n”, toes);printf(”Twice toes = %d\n", 2 * toes); printf("toes squared = %d\n", 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 <stdio.h> voidone_three(void); void two(void);int main(void){printf(”starting now:\n”); one_three();printf(”done!\n”); return 0;}void one_three(void){printf("one\n"); two();printf(”three\n”);}void two(void){printf("two\n");}Chapter 3 Programming ExercisesPE 3-。
C++ Primer英文版(第5版)《C++ Primer英文版(第5版)》基本信息作者: (美)李普曼(Lippman,S.B.) (美)拉乔伊(Lajoie,J.) (美)默Moo,B.E.) 出版社:电子工业出版社ISBN:9787121200380上架时间:2013-4-23出版日期:2013 年5月开本:16开页码:964版次:5-1所属分类:计算机 > 软件与程序设计 > C++ > C++内容简介计算机书籍 这本久负盛名的C++经典教程,时隔八年之久,终迎来史无前例的重大升级。
除令全球无数程序员从中受益,甚至为之迷醉的——C++大师Stanley B. Lippman的丰富实践经验,C++标准委员会原负责人Josée Lajoie对C++标准的深入理解,以及C++先驱Barbara E. Moo在C++教学方面的真知灼见外,更是基于全新的C++11标准进行了全面而彻底的内容更新。
非常难能可贵的是,《C++ Primer英文版(第5版)》所有示例均全部采用C++11标准改写,这在经典升级版中极其罕见——充分体现了C++语言的重大进展极其全面实践。
书中丰富的教学辅助内容、醒目的知识点提示,以及精心组织的编程示范,让这本书在C++领域的权威地位更加不可动摇。
无论是初学者入门,或是中、高级程序员提升,本书均为不容置疑的首选。
目录《c++ primer英文版(第5版)》prefacechapter 1 getting started 11.1 writing a simple c++program 21.1.1 compiling and executing our program 31.2 afirstlookat input/output 51.3 awordaboutcomments 91.4 flowofcontrol 111.4.1 the whilestatement 111.4.2 the forstatement 131.4.3 readinganunknownnumberof inputs 141.4.4 the ifstatement 171.5 introducingclasses 191.5.1 the sales_itemclass 201.5.2 afirstlookatmemberfunctions 231.6 thebookstoreprogram. 24chaptersummary 26definedterms 26part i the basics 29chapter 2 variables and basic types 312.1 primitivebuilt-intypes 322.1.1 arithmetictypes 322.1.2 typeconversions 352.1.3 literals 382.2 variables 412.2.1 variabledefinitions 412.2.2 variabledeclarations anddefinitions 44 2.2.3 identifiers 462.2.4 scopeof aname 482.3 compoundtypes 502.3.1 references 502.3.2 pointers 522.3.3 understandingcompoundtypedeclarations 57 2.4 constqualifier 592.4.1 references to const 612.4.2 pointers and const 622.4.3 top-level const 632.4.4 constexprandconstantexpressions 652.5 dealingwithtypes 672.5.1 typealiases 672.5.2 the autotypespecifier 682.5.3 the decltypetypespecifier 702.6 definingourowndatastructures 722.6.1 defining the sales_datatype 722.6.2 using the sales_dataclass 742.6.3 writing our own header files 76 chaptersummary 78definedterms 78chapter 3 strings, vectors, and arrays 813.1 namespace usingdeclarations 823.2 library stringtype 843.2.1 defining and initializing strings 843.2.2 operations on strings 853.2.3 dealing with the characters in a string 90 3.3 library vectortype 963.3.1 defining and initializing vectors 973.3.2 adding elements to a vector 1003.3.3 other vectoroperations 1023.4 introducingiterators 1063.4.1 usingiterators 1063.4.2 iteratorarithmetic 1113.5 arrays 1133.5.1 definingandinitializingbuilt-inarrays 113 3.5.2 accessingtheelementsof anarray 1163.5.3 pointers andarrays 1173.5.4 c-stylecharacterstrings 1223.5.5 interfacingtooldercode 1243.6 multidimensionalarrays 125chaptersummary 131definedterms 131chapter 4 expressions 1334.1 fundamentals 1344.1.1 basicconcepts 1344.1.2 precedenceandassociativity 1364.1.3 orderofevaluation 1374.2 arithmeticoperators 1394.3 logical andrelationaloperators 1414.4 assignmentoperators 1444.5 increment anddecrementoperators 1474.6 thememberaccessoperators 1504.7 theconditionaloperator 1514.8 thebitwiseoperators 1524.9 the sizeofoperator 1564.10 commaoperator 1574.11 typeconversions 1594.11.1 thearithmeticconversions 1594.11.2 other implicitconversions 1614.11.3 explicitconversions 1624.12 operatorprecedencetable 166 chaptersummary 168definedterms 168chapter 5 statements 1715.1 simple statements 1725.2 statementscope 1745.3 conditional statements 1745.3.1 the ifstatement 1755.3.2 the switchstatement 1785.4 iterativestatements 1835.4.1 the whilestatement 1835.4.2 traditional forstatement 1855.4.3 range forstatement 1875.4.4 the do whilestatement 1895.5 jumpstatements 1905.5.1 the breakstatement 1905.5.2 the continuestatement 1915.5.3 the gotostatement 1925.6 tryblocks andexceptionhandling 1935.6.1 a throwexpression 1935.6.2 the tryblock 1945.6.3 standardexceptions 197 chaptersummary 199definedterms 199chapter 6 functions 2016.1 functionbasics 2026.1.1 localobjects 2046.1.2 functiondeclarations 2066.1.3 separatecompilation 2076.2 argumentpassing 2086.2.1 passingargumentsbyvalue 2096.2.2 passingargumentsbyreference 2106.2.3 constparametersandarguments 2126.2.4 arrayparameters 2146.2.5 main:handlingcommand-lineoptions 218 6.2.6 functionswithvaryingparameters 2206.3 return types and the returnstatement 222 6.3.1 functionswithnoreturnvalue 2236.3.2 functionsthatreturnavalue 2236.3.3 returningapointer toanarray 2286.4 overloadedfunctions 2306.4.1 overloadingandscope 2346.5 features forspecializeduses 2366.5.1 defaultarguments 2366.5.2 inline and constexprfunctions 2386.5.3 aids for debugging 2406.6 functionmatching 2426.6.1 argumenttypeconversions 2456.7 pointers tofunctions 247 chaptersummary 251definedterms 251chapter 7 classes 2537.1 definingabstractdatatypes 2547.1.1 designing the sales_dataclass 2547.1.2 defining the revised sales_dataclass 256 7.1.3 definingnonmemberclass-relatedfunctions 260 7.1.4 constructors 2627.1.5 copy,assignment, anddestruction 2677.2 accesscontrol andencapsulation 2687.2.1 friends 2697.3 additionalclassfeatures 2717.3.1 classmembersrevisited 2717.3.2 functions that return *this 2757.3.3 classtypes 2777.3.4 friendshiprevisited 2797.4 classscope 2827.4.1 namelookupandclassscope 2837.5 constructorsrevisited 2887.5.1 constructor initializerlist 2887.5.2 delegatingconstructors 2917.5.3 theroleof thedefaultconstructor 2937.5.4 implicitclass-typeconversions 2947.5.5 aggregateclasses 2987.5.6 literalclasses 2997.6 staticclassmembers 300chaptersummary 305definedterms 305contents xipart ii the c++ library 307chapter 8 the io library 3098.1 the ioclasses 3108.1.1 nocopyorassignfor ioobjects 3118.1.2 conditionstates 3128.1.3 managingtheoutputbuffer 3148.2 file input and output 3168.2.1 using file stream objects 3178.2.2 file modes 3198.3 stringstreams 3218.3.1 using an istringstream 3218.3.2 using ostringstreams 323chaptersummary 324definedterms 324chapter 9 sequential containers 3259.1 overviewof the sequentialcontainers 3269.2 containerlibraryoverview 3289.2.1 iterators 3319.2.2 containertypemembers 3329.2.3 begin and endmembers 3339.2.4 definingandinitializingacontainer 3349.2.5 assignment and swap 3379.2.6 containersizeoperations 3409.2.7 relationaloperators 3409.3 sequentialcontaineroperations 3419.3.1 addingelements toasequentialcontainer 3419.3.2 accessingelements 3469.3.3 erasingelements 3489.3.4 specialized forward_listoperations 3509.3.5 resizingacontainer 3529.3.6 containeroperationsmayinvalidateiterators 353 9.4 how a vectorgrows 3559.5 additional stringoperations 3609.5.1 other ways to construct strings 3609.5.2 other ways to change a string 3619.5.3 stringsearchoperations 3649.5.4 the comparefunctions 3669.5.5 numericconversions 3679.6 containeradaptors 368chaptersummary 372definedterms 372chapter 10 generic algorithms 37510.1 overview. 37610.2 afirstlookat thealgorithms 37810.2.1 read-onlyalgorithms 37910.2.2 algorithmsthatwritecontainerelements 380 10.2.3 algorithmsthatreordercontainerelements 383 10.3 customizingoperations 38510.3.1 passingafunctiontoanalgorithm 38610.3.2 lambdaexpressions 38710.3.3 lambdacapturesandreturns 39210.3.4 bindingarguments 39710.4 revisiting iterators 40110.4.1 insert iterators 40110.4.2 iostream iterators 40310.4.3 reverse iterators 40710.5 structureofgenericalgorithms 41010.5.1 thefive iteratorcategories 41010.5.2 algorithmparameterpatterns 41210.5.3 algorithmnamingconventions 41310.6 container-specificalgorithms 415 chaptersummary 417definedterms 417chapter 11 associative containers 41911.1 usinganassociativecontainer 42011.2 overviewof theassociativecontainers 423 11.2.1 defininganassociativecontainer 423 11.2.2 requirements onkeytype 42411.2.3 the pairtype 42611.3 operations onassociativecontainers 428 11.3.1 associativecontainer iterators 429 11.3.2 addingelements 43111.3.3 erasingelements 43411.3.4 subscripting a map 43511.3.5 accessingelements 43611.3.6 awordtransformationmap 44011.4 theunorderedcontainers 443 chaptersummary 447definedterms 447chapter 12 dynamicmemory 44912.1 dynamicmemoryandsmartpointers 45012.1.1 the shared_ptrclass 45012.1.2 managingmemorydirectly 45812.1.3 using shared_ptrs with new 46412.1.4 smartpointers andexceptions 46712.1.5 unique_ptr 47012.1.6 weak_ptr 47312.2 dynamicarrays 47612.2.1 newandarrays 47712.2.2 the allocatorclass 48112.3 usingthelibrary:atext-queryprogram 484 12.3.1 designof thequeryprogram 48512.3.2 definingthequeryprogramclasses 487 chaptersummary 491definedterms 491part iii tools for class authors 493chapter 13 copy control 49513.1 copy,assign, anddestroy 49613.1.1 thecopyconstructor 49613.1.2 thecopy-assignmentoperator 50013.1.3 thedestructor 50113.1.4 theruleofthree/five 50313.1.5 using = default 50613.1.6 preventingcopies 50713.2 copycontrol andresourcemanagement 51013.2.1 classesthatactlikevalues 51113.2.2 definingclassesthatactlikepointers 51313.3 swap 51613.4 acopy-controlexample 51913.5 classesthatmanagedynamicmemory 52413.6 movingobjects 53113.6.1 rvaluereferences 53213.6.2 moveconstructor andmoveassignment 53413.6.3 rvaluereferencesandmemberfunctions 544 chaptersummary 549definedterms 549chapter 14 overloaded operations and conversions 551 14.1 basicconcepts 55214.2 input andoutputoperators 55614.2.1 overloading the output operator [[55714.2.2 overloading the input operator ]]. 55814.3 arithmetic andrelationaloperators 56014.3.1 equalityoperators 56114.3.2 relationaloperators 56214.4 assignmentoperators 56314.5 subscriptoperator 56414.6 increment anddecrementoperators 56614.7 memberaccessoperators 56914.8 function-calloperator 57114.8.1 lambdasarefunctionobjects 57214.8.2 library-definedfunctionobjects 57414.8.3 callable objects and function 57614.9 overloading,conversions, andoperators 57914.9.1 conversionoperators 58014.9.2 avoidingambiguousconversions 58314.9.3 functionmatchingandoverloadedoperators 587 chaptersummary 590definedterms 590chapter 15 object-oriented programming 59115.1 oop:anoverview 59215.2 definingbaseandderivedclasses 59415.2.1 definingabaseclass 59415.2.2 definingaderivedclass 59615.2.3 conversions andinheritance 60115.3 virtualfunctions 60315.4 abstractbaseclasses 60815.5 accesscontrol andinheritance 61115.6 classscopeunder inheritance 61715.7 constructors andcopycontrol 62215.7.1 virtualdestructors 62215.7.2 synthesizedcopycontrol andinheritance 62315.7.3 derived-classcopy-controlmembers 62515.7.4 inheritedconstructors 62815.8 containers andinheritance 63015.8.1 writing a basketclass 63115.9 textqueriesrevisited 63415.9.1 anobject-orientedsolution 63615.9.2 the query_base and queryclasses 63915.9.3 thederivedclasses 64215.9.4 the evalfunctions 645chaptersummary 649definedterms 649chapter 16 templates and generic programming 65116.1 definingatemplate. 65216.1.1 functiontemplates 65216.1.2 classtemplates 65816.1.3 templateparameters 66816.1.4 membertemplates 67216.1.5 controlling instantiations 67516.1.6 efficiency and flexibility 67616.2 templateargumentdeduction 67816.2.1 conversions andtemplatetypeparameters 67916.2.2 function-templateexplicitarguments 68116.2.3 trailing return types and type transformation 683 16.2.4 functionpointers andargumentdeduction 68616.2.5 templateargumentdeductionandreferences 68716.2.6 understanding std::move 69016.2.7 forwarding 69216.3 overloadingandtemplates 69416.4 variadictemplates 69916.4.1 writingavariadicfunctiontemplate 70116.4.2 packexpansion 70216.4.3 forwardingparameterpacks 70416.5 template specializations 706chaptersummary 713definedterms 713part iv advanced topics 715chapter 17 specialized library facilities 71717.1 the tupletype 71817.1.1 defining and initializing tuples 71817.1.2 using a tuple toreturnmultiplevalues 72117.2 the bitsettype 72317.2.1 defining and initializing bitsets 723 17.2.2 operations on bitsets 72517.3 regularexpressions 72817.3.1 usingtheregularexpressionlibrary 729 17.3.2 thematchandregex iteratortypes 73417.3.3 usingsubexpressions 73817.3.4 using regex_replace 74117.4 randomnumbers 74517.4.1 random-numberengines anddistribution 745 17.4.2 otherkinds ofdistributions 74917.5 the iolibraryrevisited 75217.5.1 formattedinput andoutput 75317.5.2 unformattedinput/outputoperations 761 17.5.3 randomaccess toastream 763 chaptersummary 769definedterms 769chapter 18 tools for large programs 77118.1 exceptionhandling 77218.1.1 throwinganexception 77218.1.2 catchinganexception 77518.1.3 function tryblocks andconstructors 777 18.1.4 the noexceptexceptionspecification 779 18.1.5 exceptionclasshierarchies 78218.2 namespaces 78518.2.1 namespacedefinitions 78518.2.2 usingnamespacemembers 79218.2.3 classes,namespaces,andscope 79618.2.4 overloadingandnamespaces 80018.3 multiple andvirtual inheritance 80218.3.1 multiple inheritance 80318.3.2 conversions andmultiplebaseclasses 805 18.3.3 classscopeundermultiple inheritance 807 18.3.4 virtual inheritance 81018.3.5 constructors andvirtual inheritance 813 chaptersummary 816definedterms 816chapter 19 specialized tools and techniques 819 19.1 controlling memory allocation 82019.1.1 overloading new and delete 82019.1.2 placement newexpressions 82319.2 run-timetypeidentification 82519.2.1 the dynamic_castoperator 82519.2.2 the typeidoperator 82619.2.3 usingrtti 82819.2.4 the type_infoclass 83119.3 enumerations 83219.4 pointer toclassmember 83519.4.1 pointers todatamembers 83619.4.2 pointers tomemberfunctions 83819.4.3 usingmemberfunctions ascallableobjects 84119.5 nestedclasses 84319.6 union:aspace-savingclass 84719.7 localclasses 85219.8 inherentlynonportablefeatures 85419.8.1 bit-fields 85419.8.2 volatilequalifier 85619.8.3 linkage directives: extern "c" 857chaptersummary 862definedterms 862appendix a the library 865a.1 librarynames andheaders 866a.2 abrieftourof thealgorithms 870a.2.1 algorithms tofindanobject 871a.2.2 otherread-onlyalgorithms 872a.2.3 binarysearchalgorithms 873a.2.4 algorithmsthatwritecontainerelements 873a.2.5 partitioningandsortingalgorithms 875a.2.6 generalreorderingoperations 877a.2.7 permutationalgorithms 879a.2.8 setalgorithms forsortedsequences 880a.2.9 minimumandmaximumvalues 880a.2.10 numericalgorithms 881a.3 randomnumbers 882a.3.1 randomnumberdistributions 883a.3.2 randomnumberengines 884本图书信息来源:中国互动出版网。
C++Primer笔记 1 C++ Primer 笔记
leilei 2013-8-2 C++Primer笔记 2 目录
第二章开始学习c++ ................................................................................................................................................................ 1 第三章数据处理 ....................................................................................................................................................................... 1 3.1简单变量 ..................................................................................................................................................................... 1 3.2 const限定符 ............................................................................................................................................................... 2 3.3浮点数 ......................................................................................................................................................................... 2 3.4 c++算术操作符 ........................................................................................................................................................... 2 第四章复合类型 ....................................................................................................................................................................... 2 4.1数组(array) ............................................................................................................................................................. 2 4.2 字符串 ........................................................................................................................................................................ 3 4.3 string类简介 ............................................................................................................................................................... 4 4.4 结构(struct)简介 ........................................................................................................................................................ 4 4.5 共用体(union) ....................................................................................................................................................... 5 4.6枚举类型(enum) ......................................................................................................................................................... 5 4.7指针和自由存储空间 ................................................................................................................................................. 5 4.8指针、数组和指针算术 ............................................................................................................................................. 6 第五章循环和关系表达式 ....................................................................................................................................................... 7 5.3while循环 .................................................................................................................................................................... 7 5.5循环文本输入 ............................................................................................................................................................. 8 5.6嵌套循环和二维数组 ................................................................................................................................................. 8 第六章分支语句和逻辑操作符 ............................................................................................................................................... 8 第七章函数——c++的程序模块 ............................................................................................................................................. 9 7.3函数与数组 ................................................................................................................................................................. 9 7.9函数指针 ..................................................................................................................................................................... 9 第八章函数探幽 ....................................................................................................................................................................... 9 8.1内联函数 ..................................................................................................................................................................... 9 8.2引用变量 ................................................................................................................................................................... 10 8.3默认参数 ................................................................................................................................................................... 12 8.4函数重载 ................................................................................................................................................................... 12 8.5函数模板 ................................................................................................................................................................... 12 8.6总结 ........................................................................................................................................................................... 13 第九章内存模型和名称空间 ................................................................................................................................................. 13 9.1单独编译 ................................................................................................................................................................... 13 9.2存储持续性、作用域和链接性 ............................................................................................................................... 13 9.3布局new操作符 ...................................................................................................................................................... 15 9.4名称空间 ................................................................................................................................................................... 15 第十章对象和类 ..................................................................................................................................................................... 16 10.1过程性编程和面向对象编程 ................................................................................................................................. 16 10.2抽象和类 ................................................................................................................................................................. 16 10.3类的构造函数和析构函数 ..................................................................................................................................... 17 10.4 this指针 .................................................................................................................................................................. 18 10.5对象数组 ................................................................................................................................................................. 19 10.7类作用域 ................................................................................................................................................................. 19 10.9总结 ......................................................................................................................................................................... 19 第十一章使用类 ..................................................................................................................................................................... 19