CPrimerPlus第版编程练习答案已
cprimer plus第版编程练习答案已
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;}。
c++primerplus课后编程练习答案
第二章:开始学习C++ n”;}<<endl;return 0;}double C2F(double t){return *t+32;}<<endl;return 0;}double convert(double t){return 63240*t;n";return 0;}style(miles per gallon):"<<endl;cout<<Euro_style<<" L/100Km = "<<*Euro_style<<" mpg\n";return 0;}Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):Converts to . style(miles per gallon):L/100Km = mpgPress any key to continuestyle(miles per gallon):";double US_style;cin>>US_style;cout<<"Converts to European style(miles per gallon):"<<endl;cout<<US_style<<" mpg = "<< *US_style<<"L/100Km\n";return 0;}style(miles per gallon):19Converts to European style(miles per gallon):19 mpg = 100KmPress any key to continue第四章复合类型n";return 0;}rand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;}return 0;}rand="A";eight=;snack[0].calory=200;snack[1].brand="B";snack[1].weight=;snack[1].calory=400;snack[2].brand="C";snack[2].weight=;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;}et();car* ps=new car[num];for(int i=0;i<num;++i){cout<<"Car #"<<i+1<<":\n";cout<<"Please enter the make: ";getline(cin,ps[i].name);cout<<"Please enter the year made: ";(cin>>ps[i].year).get();}cout<<"Here is your collection:\n";for(int i=0;i<num;++i)cout<<ps[i].year<<" "<<ps[i].name<<endl;delete [] ps;return 0;}n";return 0;}n";return 0;};for(int k=0;k<=i;++k)cout<<"*";cout<<endl;}return 0;}。
c-primer-plus编程习题答案
5.编写一个程序,创建一个名为toes的整数变量。让程序把toes设置为10。再让程序计算两个toes的和 以及toes的平方。程序应该输出所有的3个值,并分别标识它们。
#include<stdio.h>
int main(void) { int toes=10; int toes_add; int toes_square; toes_add=toes+toes; toes_square=toes*toes; printf("toes=%d\ntoes_add=%d\ntoes_square=%d\n",toes,toes_add,toes_square); return(0); }
第三章 数据和C
编程练习
1.通过试验的方法(即编写带有此类问题的程序)观察系统如何处理整数上溢、浮点数上溢和浮点数下 溢的情况。
#include<stdio.h> int main(void) { unsigned int a=4294967295; float b=3.4E38; float c=b*10; float d=0.1234E-2; printf("%u+1=%u\n",a,a+1); printf("%e*10=%e\n",b,c); printf("%f/10=%f\n",d,d/10); return(0); }
2.编写一个程序,要求输入一个ASCII码值(如66),然后输出相应的字符。
#include<stdio.h> int main(void) { char a; scanf("%d",&a); printf("%c\n",a); return(0); }
C-primer-plus(第五版)课后编程练习答案
第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。
该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸= cm)的程序。
他们希望建立的该程序可提示用户输入英寸值。
您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。
1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束.第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。
输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句'第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<>int main(void){、printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);},2.编写一个程序输出您的姓名及地址。
#include<>int main(void){printf("Name:He Jin\n");…printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。
不用考虑平年( fractional year)和闰年(leapyear)的问题。
#include<>(int main(void){int age=22;printf("Age:%d\n",age);printf("Day:%d\n",age*356);return(0);}%4.编写一个能够产生下面输出的程序:For he's a jolly good fellow!For he's a jolly good fellow!For he's a jolly good fellow!Which nobody can deny!程序中除了main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。
C-primer-plus(第五版)课后编程练习答案(完整)精编版
7.编写一个程序,程序中要调用名为 one_three()的函数。该函数要在一行中显示单词"one", 再调用 two()函数, 然后再在另一行中显示单词"three"。 函数 two()应该能在一行中显示单词"two"。 main() 函数应该在调用 one_three()函数之前显示短语"starting now:",函数调用之后要显示"done!"o 这样, 最后的输出结果应如下所示: starting now one two three done !
第4章 编程练习
字符串和格式化输入/输出
1.编写一个程序,要求输入名字和姓氏,然后以“名字,姓氏”的格式打印。
#include<stdio.h> int main(void) { char surname[20],firstname[20]; printf("Please input your firstname and surname:"); scanf("%s",firstname); scanf("%s",surname); printf("You are %s,%s.\n",firstname,surname); return(0); }
3.编写一个程序,把您的年龄转换成天数并显示二者的值。不用考虑平年 ( fractional year) 和闰年(leapyear)的问题。
#include<stdio.h> int main(void) { int age=22; printf("Age:%d\n",age); printf("Day:%d\n",age*356); return(0); }
【C++PrimerPlus】编程练习答案——第12章
【C++PrimerPlus】编程练习答案——第12章 1// chapter12_1_cow.h234 #ifndef LEARN_CPP_CHAPTER12_1_COW_H5#define LEARN_CPP_CHAPTER12_1_COW_H67class Cow {8private:9char name_[20];10char * hobby_;11double weight_;12public:13 Cow();14 Cow(const char * name, const char * hobby, double weight);15 Cow(const Cow & c);16 ~Cow();17 Cow & operator=(const Cow & c);18void showcow() const;19 };202122#endif//LEARN_CPP_CHAPTER12_1_COW_H232425// chapter12_1_cow.cpp2627 #include "chapter12_1_cow.h"28 #include <cstring>29 #include <iostream>3031 Cow::Cow() {32 name_[0] = '\0';33 hobby_ = nullptr;34 weight_ = 0;35 }3637 Cow::Cow(const char * name, const char * hobby, double weight) {38 strcpy(name_, name);39 hobby_ = new char[strlen(hobby)];40 strcpy(hobby_, hobby);41 weight_ = weight;42 }4344 Cow::Cow(const Cow &c) {45 strcpy(name_, _);46if (!hobby_) delete [] hobby_;47 hobby_ = new char[strlen(c.hobby_)];48 strcpy(hobby_, c.hobby_);49 weight_ = c.weight_;50 }5152 Cow::~Cow() {53delete [] hobby_;54 }5556 Cow & Cow::operator=(const Cow & c) {57 strcpy(name_, _);58if (!hobby_) delete [] hobby_;59 hobby_ = new char[strlen(c.hobby_)];60 strcpy(hobby_, c.hobby_);61 weight_ = c.weight_;62return *this;63 }6465void Cow::showcow() const {66using namespace std;67 cout << "name: " << name_ << endl68 << "hobby: " << hobby_ << endl69 << "weight: " << weight_ << endl;70 }7172// run7374void ch12_1() {75 Cow a("nma", "tennis", 70);76 Cow b("nmb", "football", 65);77 a.showcow();78 b.showcow();79 b = a;80 b.showcow();81 Cow c(a);82 c.showcow();83 }// chapter12_2_string2.h#ifndef LEARN_CPP_CHAPTER12_2_STRING2_H#define LEARN_CPP_CHAPTER12_2_STRING2_H#include <iostream>using std::istream;using std::ostream;class string2 {private:char * str;int len;static int num_strings;static const int CINLIM = 80;public:string2();string2(const string2 & s);string2(const char * s);~string2();int length() const {return len;}int charnum(char ch) const; // dstring2 & stringlow(); // bstring2 & stringup(); // cstring2 & operator=(const string2 & s);string2 & operator=(const char * s);char & operator[](int i);const char & operator[](int i) const;friend bool operator<(const string2 & s1, const string2 & s2); friend bool operator>(const string2 & s1, const string2 & s2); friend bool operator==(const string2 & s1, const string2 & s2); friend ostream & operator<<(ostream & os, const string2 & s); friend istream & operator>>(istream & is, string2 & s);friend string2 & operator+(string2 & s1, const string2 & s2); // a static int howmany();};#endif//LEARN_CPP_CHAPTER12_2_STRING2_H// chapter12_2_string2.cpp#include "chapter12_2_string2.h"#include <cstring>#include <cctype>int string2::num_strings = 0;string2::string2() {len = 4;str = new char[1];str[0] = '\0';++ num_strings;}string2::string2(const string2 &s) {len = s.length();str = new char[len + 1];std::strcpy(str, s.str);++ num_strings;}string2::string2(const char *s) {len = std::strlen(s);str = new char[len + 1];std::strcpy(str, s);++ num_strings;}string2::~string2() {delete [] str;-- num_strings;}string2 &string2::operator=(const string2 &s) {if (this == &s)return *this;delete [] str;len = s.length();str = new char[len + 1];std::strcpy(str, s.str);return *this;}string2 &string2::operator=(const char *s) {delete [] str;len = std::strlen(s);str = new char[len + 1];std::strcpy(str, s);return *this;}char &string2::operator[](int i) {return str[i];}const char &string2::operator[](int i) const {return str[i];}int string2::howmany() {return num_strings;}bool operator<(const string2 & s1, const string2 & s2) { return (std::strcmp(s1.str, s2.str) < 0);}bool operator>(const string2 & s1, const string2 & s2) { return s2 < s1;}bool operator==(const string2 & s1, const string2 & s2) { return (std::strcmp(s1.str, s2.str) == 0);}ostream & operator<<(ostream & os, const string2 & s) { os << s.str;return os;}istream & operator>>(istream & is, string2 & s) {char temp[string2::CINLIM];is.get(temp, string2::CINLIM);if (is)s = temp;while (is && is.get() != '\n')continue;return is;}int string2::charnum(char ch) const {int i = 0, num = 0;while (str[i] != '\0') {if (str[i] == ch)++ num;++ i;}return num;}string2 &string2::stringlow() {int i = 0;while (str[i] != '\0') {if (std::isalpha(str[i]))str[i] = std::toupper(str[i]);++ i;}return *this;}string2 &string2::stringup() {int i = 0;while (str[i] != '\0') {if (std::isalpha(str[i]))str[i] = std::tolower(str[i]);++ i;}}string2 & operator+(string2 & s1, const string2 & s2) {char * temp = new char[s1.len];std::strcpy(temp, s1.str);delete [] s1.str;s1.str = new char[s1.len + s2.len + 1];s1.len += s2.len;std::strcpy(s1.str, temp);std::strcat(s1.str, s2.str);return s1;}// runvoid ch12_2() {using namespace std;string2 s1(" and I am a C++ student.");string2 s2 = "Please enter your name: ";string2 s3;cout << s2;cin >> s3;string2 t("My name is ");s2 = t + s3;cout << s2 << ".\n";s2 = s2 + s1;s2.stringup();cout << "The string\n" << s2 << "\ncontains " << s2.charnum('A')<< " 'A' characters in it.\n";s1 = "red";string2 rgb[3] = {string2(s1), string2("green"), string2("blue")};cout << "Enter the name of a primary color for mixing light: ";string2 ans;bool success = false;while (cin >> ans) {ans.stringlow();for (int i = 0; i < 3; ++ i) {if (ans == rgb[i]) {cout << "That's right!\n";success = true;break;}}if (success)break;elsecout << "Try again!\n";}cout << "Bye\n";}1// chapter12_3_stock.h234void ch12_2() {5using namespace std;6 string2 s1(" and I am a C++ student.");7 string2 s2 = "Please enter your name: ";8 string2 s3;9 cout << s2;10 cin >> s3;11 string2 t("My name is ");12 s2 = t + s3;13 cout << s2 << ".\n";14 s2 = s2 + s1;15 s2.stringup();16 cout << "The string\n" << s2 << "\ncontains " << s2.charnum('A')17 << " 'A' characters in it.\n";18 s1 = "red";19 string2 rgb[3] = {string2(s1), string2("green"), string2("blue")};20 cout << "Enter the name of a primary color for mixing light: ";21 string2 ans;22bool success = false;23while (cin >> ans) {24 ans.stringlow();25for (int i = 0; i < 3; ++ i) {26if (ans == rgb[i]) {27 cout << "That's right!\n";28 success = true;29break;30 }31 }32if (success)34else35 cout << "Try again!\n";36 }37 cout << "Bye\n";38 }394041// chapter12_3_stock.cpp4243 #include "chapter12_3_stock.h"4445 #include <iostream>46 #include <cstring>4748 stock::stock() {49 company = new char[8];50 len = 7;51 strcpy(company, "no name");52 shares = 0;53 share_val = 0.0;54 total_val = 0.0;55 }5657 stock::stock(const char * co, long n, double pr) {58 len = strlen(co);59 company = new char[len + 1];60 strcpy(company, co);61if (n < 0) {62 std::cout << "Number of shares can't be negative; "63 << company << " shares set to 0.\n";64 shares = 0;65 }66else67 shares = n;68 share_val = pr;69 set_tot();70 }7172 stock::~stock() {73delete [] company;74 }7576void stock::buy(long num, double price) {77if (num < 0) {78 std::cout << "Number of shares purchased can't be nagetive. "79 << "Transaction is aborted.\n";80 }81else {82 shares += num;83 share_val = price;84 set_tot();85 }86 }8788void stock::sell(long num, double price) {89using std::cout;90if (num < 0) {91 cout << "Number of shares sold can't be negative. "92 << "Transaction is aborted.\n";93 }94else {95 shares -= num;96 share_val = price;97 set_tot();98 }99 }100101void stock::update(double price) {102 share_val = price;103 set_tot();104 }105106void stock::show() const {107using std::cout;108using std::ios_base;109 ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield); 110 std::streamsize prec = cout.precision(3);111 cout << "Company: " << company112 << " Shares: " << shares << '\n';113 cout << "Shares Prices: $" << share_val << '\n';114 cout.precision(2);115 cout << "Total Worth: $" << total_val << '\n';116 cout.setf(orig, ios_base::floatfield);117 cout.precision(prec);118 }119120const stock &stock::topval(const stock &s) const {121if (s.total_val > total_val)122return s;123return *this;124 }125126 std::ostream &operator<<(std::ostream & os, const stock & s) { 127 os << "Company: " << pany128 << " Shares: " << s.shares << '\n';129 os << "Shares Prices: $" << s.share_val << '\n';130 os.precision(2);131 os << "Total Worth: $" << s.total_val << '\n';132 }133134135// run136137138139void ch12_3() {140using namespace std;141const int STKS = 4;142 stock ss[STKS] = {143 stock("NanoSmart", 12, 20.0),144 stock("Boffo Objects", 200, 2.0),145 stock("Monolithic Obelisks", 130, 3.25),146 stock("Fleep Enterprises", 60, 6.5)147 };148 cout << "Stock holdings: \n";149int st;150for (st = 0; st < STKS; ++ st)151 cout << ss[st];152const stock * top = &ss[0];153for (st = 1; st < STKS; ++ st)154 top = &top -> topval(ss[st]);155 cout << "\nMost valuable holding:\n";156 cout << *top;157 }1// chapter12_4_stack.h234 #ifndef LEARN_CPP_CHAPTER12_4_STACK_H5#define LEARN_CPP_CHAPTER12_4_STACK_H67 typedef unsigned long Item;89class Stack {10private:11enum {MAX = 10};12 Item * pitems;13int size;14int top;15public:16 Stack(int n = MAX);17 Stack(const Stack & st);18 ~Stack();19bool isempty() const;20bool isfull() const;21bool push(const Item & item);22bool pop(Item & item);23void show() const;24 Stack & operator=(const Stack & st);25 };2627282930#endif//LEARN_CPP_CHAPTER12_4_STACK_H3132// chapter12_4_stack.cpp3334 #include "chapter12_4_stack.h"35 #include <iostream>3637 Stack::Stack(int n) {38 pitems = new Item[n];39 size = n;40 top = 0;41 }4243 Stack::Stack(const Stack &st) {44 pitems = new Item[st.size];45 size = st.size;46 top = st.top;47for (int i = 0; i < st.top; ++ i)48 pitems[i] = st.pitems[i];49 }5051 Stack::~Stack() {52delete [] pitems;53 }5455bool Stack::isempty() const {56if (top == 0)57return true;58return false;59 }6061bool Stack::isfull() const {62if (top == size)63return true;64return false;65 }6667bool Stack::push(const Item &item) {68if (isfull())69return false;70 pitems[top ++] = item;71return true;72 }7374bool Stack::pop(Item &item) {75if (isempty())76return false;77 item = pitems[-- top];78return true;79 }8081 Stack &Stack::operator=(const Stack &st) { 82if (this == &st)83return *this;84if (pitems)85delete [] pitems;86 pitems = new Item[st.size];87 size = st.size;88 top = st.top;89for (int i = 0; i < st.top; ++ i)90 pitems[i] = st.pitems[i];91return *this;92 }9394void Stack::show() const {95using namespace std;96 cout << "Stack: ";97for (int i = 0; i < top; ++ i)98 cout << pitems[i] << "";99 cout << endl;100 }101102// run103104void ch12_4() {105 Stack s1(15);106 s1.show();107 s1.push(1234);s1.push(123);s1.push(12); 108 s1.show();109 Item t = 0;110 s1.pop(t);111 s1.show();112113 Stack s2(s1);114 s2.show();115 s2.push(12345);116 s2.show();117118 Stack s3 = s1;119 s3.show();120 s3.pop(t);121 s3.show();122 }// ch12_5&6// 待更新欢迎⼤家⼀起交流。
C++ primer plus 编程练习(2-4)答案
C++ primer plus第二章到第四章编程练习答案注:本人暑假正在看这本书,顺便就把题目做了,均经过了编译器通过,无注释。
第二章1:#include<iostream>#define max 10using namespace std;void main(){char name[max],dizhi[max];cout<<"请输入姓名: ";cin>>name;cout<<"请输入地址: ";cin>>dizhi;cout<<"姓名--->"<<name<<"\t地址--->"<<dizhi<<endl;}2:#include<iostream>using namespace std;void main(){long juli;cout<<"请输入距离long(1 long 为220码):";cin>>juli;cout<<"按照您输入的距离是:"<<juli*220<<"码"<<endl; }3:#include<iostream>using namespace std;void blind(){cout<<"Three blind mice\n";}void run(){cout<<"See how they run\n";}void main(){for(int i=0;i<2;i++)blind();for(int j=0;j<2;j++)run();}4:#include<iostream>using namespace std;void month(int age){cout<<"该年龄一共包含"<<age*12<<"个月!\n"; }void main(){int age;cout<<"请输入年龄:";cin>>age;month(age);}5:#include<iostream>using namespace std;double fahrenheit(double celsius){return 1.8*celsius+32.0;}void main(){double celsius;cout<<"please enter a celsius value:";cin>>celsius;cout<<celsius<<" degrees celsius is "<<fahrenheit(celsius)<<" degrees fahrenheit.\n";}6:#include<iostream>using namespace std;double astronomical(double light){return 63240*light;}void main(){double light;cout<<"Enter the number of light years:";cin>>light;cout<<light<<" light years = "<<astronomical(light)<<"astronomical units.\n";}7:#include<iostream>using namespace std;void display(int hours,int minutes){cout<<"Time: "<<hours<<":"<<minutes<<endl; }void main(){int hour,minute;cout<<"please input the time of hour:";cin>>hour;cout<<"please input the time of minute:";cin>>minute;display(hour,minute);}第三章1:#include<iostream>using namespace std;const float danwei=0.0833333;void iswap(int cun){cout<<"您的身高为: "<<cun*danwei<<" 英尺!"<<endl;}void main(){int cun;cout<<"请输入英寸单位的身高(整数):_______\b\b\b\b\b\b";cin>>cun;iswap(cun);}2:#include<iostream>using namespace std;const double yingchi=12;const double bang=2.2;const double memter=0.0245;void caculate(double chi,double cun,double weight){double BMI;double yingcun,mi,qianke;yingcun=cun+chi*yingchi;mi=yingcun*memter;qianke=weight/bang;BMI=qianke/(mi*mi);cout<<"您的BMI值为: "<<BMI<<endl;}void main(){double chi,cun,weight;cout<<"请输入身高(以几英尺几英寸方式输入): ";cin>>chi>>cun;cout<<"请输入体重(以磅为单位): ";cin>>weight;caculate(chi,cun,weight);}3:#include<iostream>using namespace std;void main(){double degrees,minutes,seconds,sum;cout<<"Enter a latitude in degrees,minutes,and seconds:"<<endl;cout<<"First,enter the degrees: ";cin>>degrees;cout<<"Next,enter the minutes of arc: ";cin>>minutes;cout<<"Finally,enter the seconds of arc: ";cin>>seconds;sum=degrees+minutes/60+seconds/3600;cout<<degrees<<" degrees,"<<minutes<<" minutes,"<<seconds<<" seconds= "<<sum<<" degrees."<<endl;}4:#include<iostream>using namespace std;const long m=60;const long h=60;const long d=24;int sumday(long seconds){long hour,minute;minute=seconds/m;hour=minute/h;return hour/d;}int sumhour(long seconds,int day){long minute;seconds=seconds-day*d*h*m;minute=seconds/m;return minute/h;}int summinute(long seconds,int day,int hour){seconds=seconds-(day*d*h*m+hour*h*m);return seconds/m;}int sumsecond(long seconds,int day,int hour,int minute){return seconds=seconds-(day*d*h*m+hour*h*m+minute*m); }void main(){long seconds;int day,hour,minute,second;cout<<"Enter the number of seconds: ";cin>>seconds;day=sumday(seconds);hour=sumhour(seconds,day);minute=summinute(seconds,day,hour);second=sumsecond(seconds,day,hour,minute);cout<<seconds<<" seconds = "<<day<<" days,"<<hour<<" hours,"<<minute<<" minutes,"<<second<<" seconds."<<endl;}5:#include<iostream>using namespace std;void main(){double world,us;cout<<"Enter the world's population: ";cin>>world;cout<<"Enter the population of the us: ";cin>>us;double bilv;bilv=us/world;cout<<"The population of the us is "<<bilv<<"% of the world population."<<endl;}6:#include<iostream>using namespace std;void main(){float memter,jialun;cout<<"以美国风格还是欧洲风格显示耗油量?m为美国,o 为欧洲!"<<endl;cout<<"请输入(m或o):";char c;cin>>c;if(c=='m'){cout<<"请输入驱车里程(英里):";cin>>memter;cout<<"请输入使用汽油量(加仑):";cin>>jialun;cout<<"汽车耗油量为:"<<memter/jialun<<"mpg."<<endl;}else{cout<<"请输入驱车里程(公里):";cin>>memter;cout<<"请输入使用汽油量(升):";cin>>jialun;float ofg;ofg=(100*jialun)/memter;cout<<"汽车耗油量为:"<<ofg<<"L/100Km."<<endl;}}7:include<iostream>using namespace std;void main(){cout<<"请输入欧洲风格的汽车耗油量(每100公里消耗的汽油量(升)):";float ofg;cin>>ofg;float jialun;jialun=ofg/3.875;float haoyou;haoyou=62.14/jialun;cout<<"转换成美国风格的耗油量(一加仑的里程,mpg):"<<haoyou<<"mpg."<<endl;}第四章1:#include<iostream>#include<cstring>const int num=10;using namespace std;int main(){cout<<"What's your first name?";char first[num];cin.getline(first,num);cout<<"whst's your last name?";char last[num];cin>>last;cout<<"what letter grade do you deserve?";char grade;cin>>grade;cout<<"what's your age?";int age;cin>>age;cout<<"-------------------------------------"<<endl;cout<<"Name: "<<last<<","<<first<<endl;cout<<"Grade: "<<char (grade+1)<<endl;cout<<"Age: "<<age<<endl;return 0;}2:#include<iostream>#include<string>using namespace std;int main(){string name,dessert;cout<<"Enter your name:\n";getline(cin,name);cin.get();cout<<"Enter your favorite dessert:\n";getline(cin,dessert);cout<<"I have some delicious "<<dessert<<" for you, "<<name<<".\n";return 0;}3:#include<iostream>#include<cstring>using namespace std;int main(){cout<<"Enter,your first name: ";char first[10];cin>>first;cout<<"Enter your last name: ";char last[10];cin>>last;strcat(last,", ");strcat(last,first);cout<<"Here's the information in a single string: "<<last<<endl;return 0;}4:include<iostream>#include<string>using namespace std;int main(){cout<<"Enter,your first name: ";string first;cin>>first;cout<<"Enter your last name: ";string last;cin>>last;last=last+", ";last=last+first;cout<<"Here's the information in a single string: "<<last<<endl;return 0;}5:#include<iostream>#include<string>using namespace std;struct CandyBar{char brand[20];double weight;long calories;};int main(){CandyBar snack={ "Mocha Munch",2.3,350 };cout<<snack.brand<<endl;cout<<snack.weight<<endl;cout<<snack.calories<<endl;return 0;}6:#include<iostream>#include<string>using namespace std;struct CandyBar{char brand[20];double weight;long calories;};int main(){CandyBar snack[3]={ { "Mocha Munch",2.3,350 },{ "caorui",3.6,456 },{ "denger",4.7,877 } };for(int i=0;i<3;i++){cout<<"-----------------------"<<endl;cout<<snack[i].brand<<endl;cout<<snack[i].weight<<endl;cout<<snack[i].calories<<endl;}cout<<"-----------------------"<<endl;return 0;}7:#include<iostream>#include<string>#include<cstring>using namespace std;struct pizza{string company;double diameter;double weight;};int main(){pizza p;cout<<"Please input the company of manufacture pizza: ";getline(cin,pany);cout<<"Please input the diameter of pizza: ";cin>>p.diameter;cout<<"Please input the weight of pizza: ";cin>>p.weight;cout<<"Name : "<<pany<<",and the company name is form of "<<pany.size()<<" words."<<endl;cout<<"Diameter: "<<p.diameter<<endl;cout<<"Weight: "<<p.weight<<endl;return 0;}8:#include<iostream>#include<string>#include<cstring>using namespace std;struct pizza{string company;double diameter;double weight;};int main(){pizza *p=new pizza;cout<<"Please input the diameter of pizza: ";cin>>p->diameter;cin.get();cout<<"Please input the company of manufacture pizza: ";getline(cin,p->company);cout<<"Please input the weight of pizza: ";cin>>p->weight;cout<<"Name : "<<p->company<<",and the company name is form of "<<p->company.size()<<" words."<<endl;cout<<"Diameter: "<<p->diameter<<endl;cout<<"Weight: "<<p->weight<<endl;return 0;}9:#include<iostream>#include<string>using namespace std;struct CandyBar{char brand[20];double weight;long calories;};int main(){CandyBar *snack=new CandyBar[3];strcpy(snack->brand,"shanghai");snack->weight=1.2;snack->calories=7;strcpy((snack+1)->brand,"beijing");(snack+1)->weight=2.3;(snack+1)->calories=8;strcpy((snack+2)->brand,"guangzhou");(snack+2)->weight=3.4;(snack+2)->calories=9;for(int i=0;i<3;i++){cout<<"-----------------------"<<endl;cout<<snack[i].brand<<endl;cout<<snack[i].weight<<endl;cout<<snack[i].calories<<endl;}cout<<"-----------------------"<<endl;return 0;}10:#include<iostream>#include<string>using namespace std;int main(){double grade[3];cout<<"Please input three grades of running."<<endl;for(int i=0;i<3;i++){cout<<"The "<<i+1<<" is :";cin>>grade[i];}cout<<"一共跑了3次,平均成绩为: "<<(grade[0]+grade[1]+grade[2])/3<<" 码."<<endl;return 0;}。
cprimerplus习题答案
cprimerplus习题答案
《C Primer Plus习题答案:探索C语言编程的奥秘》
C语言是一种被广泛应用于系统编程和应用程序开发的高级编程语言。
它的简洁、高效和强大使得它成为了程序员们最喜欢的编程语言之一。
而C Primer
Plus则是一本经典的C语言教材,它的习题答案更是成为了许多学习者的宝贵
资料。
C Primer Plus习题答案不仅仅是一些简单的题目解答,更是对C语言编程的深
入探索。
通过学习这些习题答案,我们可以更好地理解C语言的基本概念和高
级特性,掌握C语言编程的技巧和方法。
在这些习题答案中,我们可以看到许多经典的C语言编程问题,比如数组操作、指针应用、字符串处理等等。
这些问题不仅考察了我们对C语言语法和语义的
理解,更重要的是锻炼了我们的编程思维和解决问题的能力。
除此之外,C Primer Plus习题答案还涉及了一些实际的编程案例,比如文件操作、内存管理、多线程编程等等。
通过这些案例的学习,我们可以更好地理解
C语言在实际项目中的应用,提高我们的编程水平和工程能力。
总的来说,C Primer Plus习题答案是一本非常有价值的C语言编程资料,它不
仅可以帮助我们更好地学习和掌握C语言的基础知识,更可以引导我们深入理
解C语言编程的奥秘,成为一名优秀的C语言程序员。
希望广大的C语言爱好
者和学习者都能够认真学习和掌握这些习题答案,不断提升自己的编程能力和
技术水平。
【C++PrimerPlus】编程练习答案——第16章
【C++PrimerPlus】编程练习答案——第16章 1// chapter16.h234 #ifndef LEARN_CPP_CHAPTER16_H5#define LEARN_CPP_CHAPTER16_H67 #include <iostream>8 #include <string>9 #include <cctype>10 #include <vector>11 #include <ctime>12 #include <cstdlib>13 #include <fstream>14 #include <algorithm>15 #include <queue>16 #include <list>17 #include <memory>1819void ch16_1();20void ch16_2();21void ch16_3();22int reduce(long * ar, int n);23void ch16_4();24 template<class T>25int reduce2(T * ar, int n);26void ch16_5();27bool newcustomer(double x);28void ch16_6();29 std::vector<int> lotto(int n, int select);30void ch16_7();31void ch16_8();32void ch16_9();3334struct Review {35 std::string title;36int rating;37 };38bool operator<(const Review & r1, const Review & r2);39bool worseThan(const Review & r1, const Review & r2);40bool FillReview(Review & rr);41void ShowReview(const std::shared_ptr <Review> & rr);42void ch16_10();4344#endif//LEARN_CPP_CHAPTER16_H1// chapter16.cpp234 #include "chapter16.h"56void ch16_1() {7using namespace std;8string str;9 cout << "input a string: ";10 getline(cin, str);11bool flag = true;12for (int i = 0; i < str.size() / 2; ++ i)13if (str[i] != str[str.size() - 1 - i]) {14 flag = false; break;15 }16 cout << (flag ? "yes!" : "no!") << endl;17 }1819void ch16_2() {20using namespace std;21string str;22 cout << "input a string: ";23 getline(cin, str);24bool flag = true;25for (int i = 0, j = str.size() - 1; i < j; ++ i, -- j) {26if (!isalpha(str[i]))27 ++i;28if (!isalpha(str[j]))29 --j;30if (i < j) {31 str[i] = tolower(str[i]);32 str[j] = tolower(str[j]);33if (str[i] != str[j]) {34 cout << str[i] << "" << str[j] << endl;35 flag = false;36break;37 }38 }39 }40 cout << (flag ? "yes!" : "no!") << endl;41 }4243void ch16_3() {44using namespace std;45const string FILENAME = "../C++PrimerPlus/testfiles/hangman.txt";46 ifstream InFile;47 InFile.open(FILENAME);48if (!InFile.is_open()) {49 cout << "file not found" << endl;50return;51 }52 vector<string> wordlist;53string t;54while (InFile >> t) {55 wordlist.push_back(t);56 t = "";57 }58 InFile.close();59 srand(time(0));60char play;61 cout << "Will you play a word game? <y/n> ";62 cin >> play;63 play = tolower(play);64while (play == 'y') {65string target = wordlist[rand() % wordlist.size()];66int length = target.length();67string attempt(length, '-');68string badchars;69int guesses = 6;70 cout << "Guess my secret word. It has " << length71 << " letters, and you guess\n"72 << "one letter at a time. You get " << guesses73 << " wrong guesses." << endl;74 cout << "Your word: " << attempt << endl;75while (guesses > 0 && attempt != target) {76char letter;77 cout << "Guess a letter: ";78 cin >> letter;79if (badchars.find(letter) != string::npos || attempt.find(letter) != string::npos) { 80 cout << "You already guessed that. Try again." << endl;81continue;82 }83int loc = target.find(letter);84if (loc == string::npos) {85 cout << "Oh, bad guess!" << endl;86 -- guesses;87 badchars += letter;88 }89else {90 cout << "Good guess!" << endl;91 attempt[loc] = letter;92 loc = target.find(letter, loc + 1);93while (loc != string::npos) {94 attempt[loc] = letter;95 loc = target.find(letter, loc + 1);96 }97 }98 cout << "Your word: " << attempt << endl;99if (attempt != target) {100if (badchars.length() > 0)101 cout << "Bad choices: " << badchars << endl;102 cout << guesses << " bad guesses left" << endl;103 }104 }105if (guesses > 0)106 cout << "That's right!" << endl;107else108 cout << "Sorry, the word is " << target << "." << endl;109 cout << "Will you play another? <y/n> ";110 cin >> play;111 play = tolower(play);112 }113 cout << "Bye! " << endl;114 }115116int reduce(long * ar, int n) {117 std::sort(ar, ar + n);118long * end = std::unique(ar, ar + n);119return int(end - ar);120 }121122void ch16_4() {123using namespace std;124long arr[5] = {3, 9, 0, 1, 1};125for (auto x : arr)126 cout << x << "\t";127 cout << endl;128int l = reduce(arr, 5);129for (int i = 0; i < l; ++ i)130 cout << arr[i] << "\t";131 cout << endl;132 }133134 template<class T>135int reduce2(T * ar, int n) {136 std::sort(ar, ar + n);137 T * end = std::unique(ar, ar + n);138return int(end - ar);139 }140141void ch16_5() {142using namespace std;143long arr[5] = {3, 9, 0, 1, 1};144for (auto x : arr)145 cout << x << "\t";146 cout << endl;147int l = reduce2(arr, 5);148for (int i = 0; i < l; ++ i)149 cout << arr[i] << "\t";150 cout << endl;151string arr2[5] = {"bb", "aa", "cc", "cc", "cc"};152for (auto x : arr2)153 cout << x << "\t";154 cout << endl;155int l2 = reduce2(arr2, 5);156for (int i = 0; i < l2; ++ i)157 cout << arr2[i] << "\t";158 cout << endl;159 }160161const int MIN_PER_HR = 60;162163bool newcustomer(double x) {164return (std::rand() * x / RAND_MAX < 1);165 }166167void ch16_6() {168// 懒得打字了,很简单。
C Primer Plus第6版编程练习测试参考答案(已下载)
Chapter 2 Programming 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)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 3 Programming ExercisesPE 3--‐2/*ProgrammingExercise3-2*/#include<stdio.h>intmain(void){intascii;printf("EnteranASCIIcode:");scanf("%d",&ascii);printf("%distheASCIIcodefor%c.\n",ascii,ascii);return0;}"%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 5 Programming ExercisesPE 5--‐1/*ProgrammingExercise5-1*/#include<stdio.h>intmain(void){constintminperhour=60;intminutes,hours,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);return0;}voidshowCube(doublex){printf("Thecubeof%eis%e.\n",x,x*x*x);}Chapter 6 Programming ExercisesPE 6--‐1/*pe6-1.c*//*thisimplementationassumesthecharactercodes*//*aresequential,astheyareinASCII.*/#include<stdio.h>#defineSIZE26intmain(void){charlcase[SIZE];inti;for(i=0;i<SIZE;i++)lPE 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*/}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("Daphne:$%.2f\n", daphne);printf("Deidre:$%.2f\n",deidre);return0;}Chapter 7 Programming ExercisesPE 7--‐1/*ProgrammingExercise7-1*/#include<stdio.h>intmain(void){charch;intsp_ct=0;intnl_ct=0;intother=0;while((ch=getchar())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{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=}final_total=cost_total+shipping-discount;printf("Yourorder:\n");printf("%.2flbsofartichokesat$%.2fperpound:$%.2f\n",lb_artichokes,price_artic hokes,cost_artichokes);printf("%.2flbsofbeetsat$%.2fperpound:$%.2f\n",lb_bee ts,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("V olumediscount:$%.2f\n",discount);printf("Shipping:$%.2f\n",shipping);printf("Totalcharges:$%.2f\n",final_total);return0;}Chapter 8 Programming 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++;}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();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 9 Programming 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){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("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;*/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 Exercises/*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;RS;year++)}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*/#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}}{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(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;}char*getword(char*str){intch;char*orig=str;//skipoverinitialwhitespacewhile((ch=getchar ())!=EOF&&isspace(ch))continue;if(ch==EOF)returnNULL;else*str++=ch;//firstcharacterinword//getrestofwordwhile((ch=getchar())!=EOF&&!isspace(ch))*str++=ch;*str='\0';if(ch==EOF)returnNULL;else{while(ch!='\n')ch=getchar();returnorig;}}PE 11--‐6#include<stdio.h>#include<string.h>#defineLEN80_Boolis_within(constchar*str,charc);char*s_gets(char*st,intn);intmain(void){charinput[LEN];charch;intfound;;printf("Enterastring:");while(s_gets(input,LEN)&&input[0]!='\0'){printf("Enteracharacter:");ch=getchar();while(getchar()!='\n')continue;found=is_within(input,ch);if(found==0)printf("%cnotfoundinstring.\n",ch);elseputs("Notfound");return0;}#include<string.h>char*string_in(constchar*s1,constchar*s2){intl2=strlen(s2);inttries;/*maximumnumberofcomparisons*/intnomatch=1;/*setto0ifmatchisfound*/ tries=strlen(s1)+1-l2;if(tries>0)while((nomatch=strncmp(s1,s2,l2))&&tries--)s1++;if(nomatch)returnNULL;elsereturn(char*)s1;/*castconstaway*/PE 11--‐10/*ProgrammingExercise11-10*/#include<stdio.h>#include<string.h>//forstrchr();#defineLEN81intdrop_space(char*s);char*s_gets(char*st,intn);intmain(void){charorig[LEN];puts("Enterastringof80charactersorless:");while(s_gets(orig,LEN)&&orig[0]!='\0'){drop_space(orig);puts(orig);puts("Enternextstring(orjustEntertoquit):");}}#include<stdbool.h>//forbool,true,falseintmain(void){charc;//readincharacterintlow_ct=0;//numberoflowercasecharactersintup_ct=0;//numberofuppercasecharactersintdig_ct=0;//numberofdigitsintn_words=0;//numberofwordsintpunc_ct=0;//numberofpunctuationmarksboolinword=false;//==trueifcisinaword printf("Entertexttobeanalyzed(EOFtoterminate):\n");while((c=getchar())!=EOF) {if(islower(c))low_ct++;elseif(isupper(c))up_ct++;elseif(isdigit(c))dig_ct++;elseif(ispunct(c))punc_ct++;if(!isspace(c)&&!inword){inword=true;//startinganewwordn_words++;//countwordif(isspace(c)&&inword)inword=false;//reachedendofword}printf("\nwords=%d,lowercase=%d,uppercase=%d," "digits=%d,punctuation=%d\n",n_words,low_ct,up_ct,dig_ct,punc_ct);return0;}PE 11--‐14/*ProgrammingExercise11-14*/#include<stdio.h>#include<stdlib.h>/*foratof()*/#include<math.h>/*forpow()*/intmain(intargc,char*argv[])}}if(ok)while((ch=getchar())!=EOF){switch(mode){case'p':putchar(ch);break;case'u':putchar(toupper(ch));break;case'l':putchar(tolower(ch));}}return0;Chapter 12 Programming ExercisesPE 12--‐1/*pe12-1.c--deglobalizingglobal.c*//*ProgrammingExercise12-1*//*oneofseveralapproaches*/#include<stdio.h>voidcritic(int*u);intmain(void){intunits;/*unitsnowlocal*/printf("Howmanypoundstoafirkinofbutter?\n");scanf("%d",&units);while(units!=56)critic(&units);printf("Youmusthavelookeditup!\n");return0;}{if(*pm!=METRIC&&*pm!=US){printf("Invalidmodespecified.Mode%d\n",*pm);printf("Previousmodewil lbeused.\n");*pm=USE_RECENT;}}voidget_info(intmode,double*pd,double*pf){if(mode==METRIC)printf("Enterdistancetraveledinkilometers:");elseprintf("Enterdistancetraveledinmiles:");scanf("%lf",pd);if(mode==Mprintf("Enterfuelconsumedinliters:");elseprintf("Enterfuelconsumedingallons:");scanf("%lf",pf);}voidshow_info(intmode,doubledistance,doublefuel){printf("Fuelconsumptionis");if(mode==METRIC)printf("%.2flitersper100km.\n",100*fuel/distance);elseprintf("%.1fmilespergallon.\n",distance/fuel);}//pe12-3b.c//compilewithpe12-3a.c#include<stdio.h>#include"pe12-3a.h"intmain(void)for(search=top+1;search<limit;search++)if(array[search]>array[top]){temp=array[search];array[search]=array[top];array[top]=temp;}}/*print.c--printsanarray*/voidprint(constintarray[],intlimit){intindex;for(index=0;index<limit;index++){printf("%2d",array[index]);if(index%10==9)putchar('\n');}if(index%10!=0)//iflastlinenotcompleteputchar('\n');}PE 12--‐7/*pe12-7.c*/#include<stdio.h>#include<stdlib.h>/*forsrand()*/#include<time.h>/*fortime()*/introllem(int);intmain(void){intdice,count,roll;intsides;intset,sets;srand((unsignedint)time(0));/*randomizerand()*/ printf("Enterthenumberofsets;enterqtostop:");while(scanf("%d",&sets)==1)}printf("Usage:%ssourcefiletargetfile\n",argv[0]);exit(EXIT_FAILURE);}if((source=fopen(argv[1],"rb"))==NULL){printf("Couldnotopenfile%sforinput\n",argv[1]);exit(EXIT_FAILURE);}if((target=fopen(argv[2],"wb"))==NULL){printf("Couldnotopenfile%sforoutput\n",argv[2]);exit(EXIT_FAILURE);}while((byte=getc(source))!=EOF){putc(byte,target);}if(fclose(source)!=0)printf("Couldnotclosefile%s\n",argv[1]);if(fclose(target)!=0)printf("Couldnotclosefile%s\n",argv[2]);return0;}PE 13--‐4/*ProgrammingExercise13-4*/#include<stdio.h>#include<stdlib.h>intmain(intargc,char*argv[]){intbyte;FILE*source;intfilect;}FILE*fa,*fs;intfiles=0;intfct;if(argc<3){printf("Usage:%sappendfilesourcefile[s]\n",argv[0]);exit(EXIT_FAILURE);}if((fa=fopen(argv[1],"a"))==NULL){fprintf(stderr,"Can'topen%s\n",argv[1]);exit(EXIT_FAILURE);}if(setvbuf(fa,NULL,_IOFBF,BUFSIZE)!=0){fputs("Can'tcreateoutputbuffer\n",stderr);exit(EXIT_FAILURE);}for(fct=2;fct<argc;fct++){if(strcmp(argv[fct],argv[1])==0)fputs("Can'tappendfiletoitself\n",stderr);els eif((fs=fopen(argv[fct],"r"))==NULL)fprintf(stderr,"Can'topen%s\n",argv[fct]);else{if(setvbuf(fs,NULL,_IOFBF,BUFSIZE)!=0){fputs("Can'tcreateoutputbuffer\n",stderr);continue;}append(fs,fa);if(ferror(fs)!=0)fprintf(stderr,"Errorinreadingfile%s.\n",argv[fct]);if(ferror(fa)!=0)fprintf(stderr,"Errorinwritingfile%s.\n",argv[1]);fclose(fs);files++;printf("File%sappended.\n",argv[fct]);}}printf("Done.%dfilesappended.\n",files);fclose(fa);return0;}{while(ch1!=EOF&&ch1!='\n')/*skippedafterEOFreached*/ {putchar(ch1);ch1=getc(f1);}if(ch1!=EOF){putchar('\n');ch1=getc(f1);}while(ch2!=EOF&&ch2!='\n')/*skippedafterEOFreached*/ {putchar(ch2);ch2=getc(f2);}if(ch2!=EOF){putchar('\n');ch2=getc(f2);}}if(fclose(f1)!=0)printf("Couldnotclosefile%s\n",argv[1]);if(fclose(f2)!=0)printf("Couldnotclosefile%s\n",argv[2]);return0;}/*ProgrammingExercise13-7b*//*codeassumesthatend-of-lineimmediatelyprecedesend-of-file*/#include<stdio.h>#include<stdlib.h>intmain(intargc,char*argv[]){intch1,ch2;FILE*f1;}putchar('\n');ch2=getc(f2);}}if(fclose(f1)!=0)printf("Couldnotclosefile%s\n",argv[1]);if(fclose(f2)!=0)printf("Couldnotclosefile%s\n",argv[2]);return0;}PE 13--‐9/*ProgrammingExercise13-9*//*tosimplifyaccounting,storesonenumberandwordperline*/#include<stdio.h>#include<stdlib.h>#defineMAX47intmain(void){FILE*fp;charwords[MAX];intwordct=0;if((fp=fopen("wordy","a+"))==NULL){fprintf(stderr,"Can'topen\"words\"file.\n");exit(EXIT_FAILURE);}//determinecurrentnumberoflinesrewind(fp);while(fgets(words,MAX,fp)!=NULL)wordct++;rewind(fp);puts("Enterwordstoaddtothe file;pressthe#");puts("keyatthebeginningofalinetoterminate.");while((fscanf(stdin,"%40s ",words)==1)&&(words[0]!='#'))fprintf(fp,"%3d:%s\n",++wordct,words);puts("Filecontents:");}return0;}PE 13--‐12: Sample Input Text009000000000589985200000000000000090000000589985520000000000000000000000581985452000000000000090000000589985045200000000009000000000589985004520000000000000000000589185000452000000000000000000589985000045200000555555555555589985555555555555888888888888589985888888888888999909999999999999999939999999888888888888589985888888888888555555555555589985555555555555000000000000589985000000000000000000000000589985000066000000000022000000589985005600650000000033000000589985056111165000000044000000589985005600650000000055000000589985000066000000000000000000589985000000000000000000000000589985000000000000PE 13--‐12/*ProgrammingExercise13-12*/#include<stdio.h>}voidinit(chararr[][COLS],charch){intr,c;for(r=0;r<ROWS;r++)for(c=0;c<COLS;c++)arr[r][c]=ch;}voidMakePic(intdata[][COLS],charpic[][COLS],introws) {introw,col;for(row=0;row<rows;row++)for(col=0;col<COLS;col++)pic[row][col]=trans[data[row][col]];}Chapter 14 Programming ExercisesPE 14--‐1/*pe14-1.c*/#include<stdio.h>#include<string.h>#include<ctype.h>structmonth{charname[10];charabbrev[4];intdays;intmonumb;};conststructmonthmonths[12]={{"January","Jan",31,1},{"February","Feb",28,2},{"March","Mar",31,3},{"April","Apr",30,4},{"May","May",31,5},{"June","Jun",30,6},{"July","Jul",31,7},{"August","Aug",31,8},}char*s_gets(char*st,intn);#defineMAXTITL40#defineMAXAUTL40#defineMAXBKS100/*maximumnumberofbooks*/structbook{/*setupbooktem plate*/chartitle[MAXTITL];charauthor[MAXAUTL];floatvalue;};voidsortt(structbook*pb[],intn);voidsortv(structbook*pb[],intn);intmain(void){structbooklibrary[MAXBKS];/*arrayofbookstructures*/structbook*pbk[MAXB KS];/*pointersforsorting*/intcount=0;intindex;printf("Pleaseenterthebooktitle.\n");printf("Press[enter]atthestartofalinetostop.\n");while(count<MAXBKS&&s_gets(library[count].title,MAXTITL)!=NULL&&library[count].title[0]!='\0'){printf("Nowentertheauthor.\n");s_gets(library[count].author,MAXAUTL);printf("Nowenterthevalue.\n");scanf("%f",&library[count].value);pbk[count]=&library[count];count++;while(getchar()!='\n')continue;/*clearinputline*/if(count<MAXBKS)printf("Enterthenexttitle.\n");}printf("Hereisthelistofyourbooks:\n");for(index=0;index<count;index++)printf("%sby%s:$%.2f\n",library[index].title,library[index].author,library[index].value);}}}char*s_gets(char*st,intn){char*ret_val;char*find;ret_val=fgets(st,n,stdin);if(ret_val){find=strchr(st,'\n');//lookfornewlineif(find)//iftheaddressisnotNULL,*find='\0';//placeanullcharacterthereelsewhile(getchar()!='\n')continue;//disposeofrestofline}returnret_val;}PE 14--‐5/*pe14-5.c*/#include<stdio.h>#include<string.h>#defineLEN14#defineCSIZE4#defineSCORES3structname{charfirst[LEN];charlast[LEN];};structstudent{structnameperson;floatscores[SCORES];floatmean;};voidget_scores(structstudentar[],intlim);voidfind_means(structstude ntar[],intlim);voidshow_class(conststructstudentar[],intlim);voidsho w_ave(conststructstudentar[],intlim);intmain(void) {structstudentclass[CSIZE]={{"Flip","Snide"},}}voidshow_class(conststructstudentar[],intlim) {inti,j;charwholename[2*LEN];for(i=0;i<lim;i++){strcpy(wholename,ar[i].person.first);strcat(wholename,"");strcat( wholename,ar[i]st);printf("%27s:",wholename);for(j=0;j<SCORES;j++)printf("%6.1f",ar[i].scores[j]);printf("Average=%5.2f\n",ar[i].mean);}}voidshow_ave(conststructstudentar[],intlim) {inti,j;floattotal;printf("\n%27s:","QUIZA VERAGES");for(j=0;j<SCORES;j++){for(total=0,i=0;i<lim;i++)total+=ar[i].scores[j];printf("%6.2f",total/lim);}for(total=0,i=0;i<lim;i++)total+=ar[i].mean;printf("All=%5.2f\n",total/lim);}PE 14--‐7/*pe14-7.c*/#include<stdio.h>#include<stdlib.h>#include<string.h>{if(count==0)puts("Currentcontentsofbook.dat:");printf("%sby%s:$%.2f\n",library[count].book.title,librar y[count].book.author,library[count].book.value);printf("Doyouwishtochangeordeletethisentry?<y/n>");if(getlet("yn")=='y'){printf("Enterctochange,dtodeleteentry:");if(getlet("cd")=='d'){library[count].delete_me=true;deleted++;puts("Entrymarkedfordeletion.");}elseupdate(&library[count]);}count++;}fclose(pbooks);}filecount=count-deleted;if(count==MAXBKS){fputs("Thebook.datfileisfull.",stderr);exit(EXIT_FAILURE);}puts("Pleaseaddnewbooktitles.");puts("Press[enter]atthestartofalinetostop.");open=0;while(filecount<MAXBKS){if(filecount<count){while(library[open].delete_me==false)open++;}}{intstatus=CONTINUE;if(s_gets(pb->book.title,MAXTITL)==NULL||pb->book.title[0]=='\0')status=DONE;else{printf("Nowentertheauthor:");s_gets(pb->book.author,MAXAUTL);printf("Nowenterthevalue:");while(scanf("%f",&pb->book.value)!=1){puts("Pleaseusenumericinput");scanf("%*s");}while(getchar()!='\n')continue;/*clearinputline*/pb->delete_me=false;}returnstatus;}voidupdate(structpack*item){structbookcopy;charc;copy=item->book;puts("Entertheletterthatindicatesyourchoice:");puts("t)modifytitlea)modifya uthor");puts("v)modifyvalues)quit,savingchanges");puts("q)quit,ignorechanges");while((c=getlet("tavsq"))!='s'&&c!='q'){switch(c){case't':puts("Enternewtitle:");s_gets(copy.title,MAXTITL);break; case'a':puts("Enternewauthor:");s_gets(copy.author,MAXAUTL);break;case'v:puts("Enternewvalue:");while(scanf("%f",©.value)!=1)#defineEMPTY0#defineTAKEN1#defineCONTINUE1#defineDONE0 structplanestats{intseat_id;intstatus;charlast[LEN];charfirst[LEN];};intgetmenu(void);intgetlet(constchar*);intopenings(conststructplanestats[],int);voidshow_empties(conststructpl anestats[],int);voidlist_assign(structplanestats*[],int);voidassign_seat(str uctplanestats[],int);voiddelete_seat(structplanestats[],int);voidshow_seats(conststructplanestats[],int);voidsort(structplanestats*[],int);voidmakeli st(conststructplanestats[],char*,int);char*s_gets(char*st,intn);。
C-primer-plus(第五版)课后编程练习答案(完整)
编程练习1.您刚刚被MacroMuscle(Software for Hard Bodies)聘用。
该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。
他们希望建立的该程序可提示用户输入英寸值。
您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。
1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。
输出应如下所示(当然里面要换成您的):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<stdio.h>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");}2.编写一个程序输出您的及地址。
#include<stdio.h>int main(void){printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。
不用考虑平年( fractional year)和闰年(leapyear)的问题。
#include<stdio.h>int main(void){int age=22;printf("Age:%d\n",age);printf("Day:%d\n",age*356);return(0);}4.编写一个能够产生下面输出的程序:For he's a jolly good fellow!For he's a jolly good fellow!For he's a jolly good fellow!Which nobody can deny!程序中除了main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。
c++primerplus课后编程练习答案
第二章:开始学习C++n”;}<<endl;return 0;}double C2F(double t){return *t+32;}<<endl;return 0;}double convert(double t){return 63240*t;n";return 0;}style(miles per gallon):"<<endl;cout<<Euro_style<<" L/100Km = "<<*Euro_style<<" mpg\n";return 0;}Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):Converts to . style(miles per gallon):L/100Km = mpgPress any key to continuestyle(miles per gallon):";double US_style;cin>>US_style;cout<<"Converts to European style(miles per gallon):"<<endl;cout<<US_style<<" mpg = "<< *US_style<<"L/100Km\n";return 0;}style(miles per gallon):19Converts to European style(miles per gallon):19 mpg = 100KmPress any key to continue第四章复合类型n";return 0;}rand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;}return 0;}rand="A";eight=;snack[0].calory=200;snack[1].brand="B";snack[1].weight=;snack[1].calory=400;snack[2].brand="C";snack[2].weight=;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;}et();car* ps=new car[num];for(int i=0;i<num;++i){cout<<"Car #"<<i+1<<":\n";cout<<"Please enter the make: ";getline(cin,ps[i].name);cout<<"Please enter the year made: ";(cin>>ps[i].year).get();}cout<<"Here is your collection:\n";for(int i=0;i<num;++i)cout<<ps[i].year<<" "<<ps[i].name<<endl;delete [] ps;return 0;}n";return 0;}n";return 0;};for(int k=0;k<=i;++k) cout<<"*";cout<<endl;}return 0;}。
C-primer-plus(第五版)课后编程练习答案
第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。
该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸= cm)的程序。
他们希望建立的该程序可提示用户输入英寸值。
您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。
1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章C语言概述编程练习《1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。
输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句)#include<>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);}[2.编写一个程序输出您的姓名及地址。
#include<>int main(void){printf("Name:He Jin\n");|printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。
不用考虑平年( fractional year)和闰年(leapyear)的问题。
#include<>int main(void){—int age=22;printf("Age:%d\n",age);printf("Day:%d\n",age*356);return(0);}4.编写一个能够产生下面输出的程序:For he's a jolly good fellow!For he's a jolly good fellow!For he's a jolly good fellow!—Which nobody can deny!程序中除了main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。
Cprimerplus(第五版)课后编程练习答案(完整)
C_primer_plus(第五版)课后编程练习答案(完整)第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。
该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。
他们希望建立的该程序可提示用户输入英寸值。
您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。
1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。
输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<stdio.h>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);}2.编写一个程序输出您的姓名及地址。
#include<stdio.h>int main(void){printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。
不用考虑平年( fractional year)和闰年(leapyear)的问题。
C Primer Plus第6版编程练习答案(已下载)之欧阳理创编
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 in years */ intagedays; /* age indays *//* 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);intmain(void){jolly();jolly();jolly();deny();return;}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=1;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("starting now:\n");one_three();printf("done!\n"); return0;}void one_three(void){printf("one\n");two();printf("three\n");}void two(void){printf("two\n");}Chapter 3 Programming Exercises PE 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){floatnum;printf("Enter a floating-point value: "); scanf("%f", &num);printf("fixed-pointnotation: %f\n", num);printf("exponentialnotation: %e\n", num);printf("p notation: %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 watermolecule in grams */ float mass_qt = 950;/* mass of quart of water in grams */ floatquarts; float molecules;printf("Enter the number of quarts ofwater: "); 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 yourfirst name: ");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 heightin inches: "); scanf("%f",&height); printf("Enteryour name: ");scanf("%s", name);printf("%s, you are %.3f feet tall\n", name, height / 12.0);return;}PE 4--‐7/* Programming Exercise 4-7 */#include<stdio.h>#include<float.h> intmain(void){ floatot_f = 1.0 /3.0;double ot_d= 1.0 / 3.0;printf(" floatvalues: ");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 ExercisesPE 5--‐1/* Programming Exercise 5-1 */#include<stdio.h> intmain(void){ const intminperhour =60; intminutes, hours,mins;printf("Enter the number ofminutes 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");return;}PE 5--‐3/* Programming Exercise 5-3 */ #include<stdio.h> intmain(void){ const intdaysperweek= 7; intdays, weeks,day_rem;printf("Enter thenumber of days: ");scanf("%d", &days);while (days > 0){ weeks =days / daysperweek;day_rem = days % daysperweek;printf("%d days are %d weeksand %d days.\n", days, weeks,day_rem);printf("Enter the number of days (0 or less to end): "); scanf("%d", &days);}printf("Done!\n"); return0;}PE 5--‐5/* ProgrammingExercise 5-5 */#include <stdio.h>int main(void) /* finds sum of first n integers */ {intcount,sum;intn;printf("Enter theupper limit: ");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 */ {doubleval;printf("Enter a floating-point value: ");scanf("%lf", &val);showCube(val); return0; }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 SIZE26 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 ){charlet ='F';charstart;charend;for (end = let; end >= 'A'; end--) {for (start = let; start >= end; start--)printf("%c", start);printf("\n");}return;}PE 6--‐6/* pe6-6.c */#include<stdio.h> intmain(void ){ intlower, upper,index; intsquare, cube;printf("Enterstarting integer: ");scanf("%d", &lower);printf("Enter endinginteger: ");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);}return;}PE 6--‐8/* pe6-8.c */#include<stdio.h> intmain(void ){doublen,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 8intmain(void ){intvals[SIZE];int i;printf("Please enter %dintegers.\n", SIZE); for (i =0; i < SIZE; i++)scanf("%d", &vals[i]);printf("Here, in reverse order, are the valuesyou 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 8intmain(void ){inttwopows[SIZE];int i;int value = 1; /* 2 to the 0 */for (i = 0; i < SIZE; i++){ twopows[i] =value;value *= 2;}i=;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 8intmain(void){ doublearr[SIZE];doublearr_cumul[SIZE];int i;printf("Enter %dnumbers:\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_COMP 0.05#defineINIT_AMT 100.0 intmain( void){doubledaphne =INIT_AMT;double deidre= INIT_AMT;int years = 0;while (deidre <= daphne) { daphne += RATE_SIMP *INIT_AMT;deidre +=RATE_COMP *deidre;++years;}printf("Investment values after %d years:\n", years); printf("Daphne:$%.2f\n", daphne); printf("Deidre:$%.2f\n", deidre); return 0;}Chapter 7 Programming Exercises PE 7--‐1/*ProgrammingExercise 7-1*/ #include<stdio.h> intmain(void){charch;intsp_ct = 0;intnl_ct = 0;intother = 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);return;}PE 7--‐3/* Programming Exercise 7-3 */#include<stdio.h> intmain(void){ int n;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 % 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 ofodds: %d", ct_odd); if(ct_odd > 0)printf(" average: %g", sumodd / ct_odd);putchar('\n');printf("\ndone\n");return;}PE 7--‐5/* Programming Exercise 7-5 */ #include<stdio.h> intmain(v oid) {char ch; intct1=0; intct2=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);return;}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 // ratefor 2nd tier #define RATE30.25 // rate for 3rd tier intmain(void){doublehours;doublegross;doublenet;doubletaxes;printf("Enter the number of hoursworked this week: "); 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);return;}PE 7--‐9/* Programming Exercise 7-9 */#include<stdio.h>#include<stdbool.h> intmain(void){intlimit;intnum;intdiv;bool numIsPrime; // use int if stdbool.h notavailableprintf("Enter a positiveinteger: "); while(scanf("%d", &limit) == 1 &&limit > 0){if (limit > 1)printf("Here are the prime numbers upthrough %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("%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 doubleprice_beets = 1.15;const doubleprice_carrots = 1.09;const doubleDISCOUNT_RATE =0.05; const doubleunder5 = 6.50; constdouble under20 =14.00; const double base20 = 14.00; const double extralb = 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("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 poundsof 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; elsediscount = 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("%.2f lbs of beets at $%.2f perpound: $%.2f\n", lb_beets,price_beets, cost_beets); printf("%.2f lbsof 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); return0; }Chapter 8 Programming Exercises PE 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);return;}PE 8--‐3/* Programming Exercise 8-3 *//* Using ctype.h eliminates need to assume consecutive coding */#include<stdio.h>#include<ctype.h>intmain(void){ int ch;unsignedlong uct =0;unsignedlong 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);return;}/* or youcould use if(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; charresponse;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 withan l if it is low.\n"); printf("Uh...is yournumber %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 doit!\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 for 2nd tier #defineRATE3 0.25 // rate for3rd tier int getfirst(void); voidmenu(void); int main(void){doublehours;doublegross;doublenet;doubletaxes;doublepay;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 hoursworked this week: "); 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");return;}void menu(void){printf("********************************************************""*********\n");printf("Enter the letter corresponding to the desired pay rate"" 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>doublemin(double,double); intmain(void){double x, y;printf("Enter two 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");return;}double min(double a, double b){return a < b ? a : b;}/* alternative implementationdouble min(doublea, double b){if(a<b)return a;elsereturnb;}*/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");return;}// start rows and colsat 0 voidchLineRow(char ch,int c, 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); intmain(void){double x, y;printf("Enter two 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");return;}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/* ProgrammingExercise 9-8 */#include <stdio.h>double power(double a, int b); /* ANSI prototype */ int main(void) { double x,xpow; int n; printf("Enter a number and the integer power"); printf(" to which\nthe number will be 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 numbers or q to quit.\n");} printf("Hope you enjoyed this power trip -- bye!\n"); return 0;} double power(double a, int b) /* function definition */{doublepow=1;inti;if(b==0){if(a==0)。
C Primer Plus 第七章编程练习参考答案
#include <stdio.h>int main(void){char ch;int sp_ct, nl_ct, other;sp_ct = nl_ct = other = 0;while ((ch = getchar()) != '#'){if (ch == ' ')sp_ct++;else if (ch == '\n')nl_ct++;elseother++;}printf("%d whitespace, %d newline, %d other.\n", sp_ct, nl_ct, other);return 0;}#include <stdio.h>int main(void){char ch;int count = 0;while ((ch = getchar()) != '#') {if (ch == '\n')continue;count ++;putchar(ch);printf("/%d ", ch);if (count % 8 == 0)printf("\n");}printf("That's all!");return 0;}#include <stdio.h>int main(void){int num;int e_ct, o_ct;double e_sum, o_sum;e_ct = o_ct = 0;e_sum = o_sum = 0.0;printf("Enter the integer:(0 to quit).\n");while (scanf("%d", &num) == 1 && num != 0) {if (num % 2 == 0){e_ct++;e_sum += num;}else{o_ct++;o_sum += num;}printf("Enter next integer:(0 to quit).\n");}printf("%d even entered.", e_ct);if (e_ct > 0)printf(" Average is %g.", e_sum / e_ct);putchar('\n');printf("%d odd entered.", o_ct);if (o_ct > 0)printf(" Average is %g.", o_sum / o_ct);putchar('\n');printf("Done!\n");return 0;}/* programming exercise 7-4 */#include <stdio.h>#define ECM '!'int main(void){char ch;int fs_ct = 0;int em_ct = 0;while ((ch = getchar()) != '#'){if (ch == '.'){putchar(ECM);fs_ct++;}else if (ch == '!'){putchar(ECM);putchar(ECM);em_ct++;}elseputchar(ch);}printf("%d times fs to em, %d times em to double em.\n", fs_ct, em_ct);return 0;}/* programming exercise 7-5 */#include <stdio.h>int main(void){int num;int e_ct = 0, o_ct = 0;double e_sum = 0.0, o_sum = 0.0;printf("Enter the integer:(0 to quit).\n");while (scanf("%d", &num) == 1 && num != 0) {switch(num % 2){case 0:e_ct++;e_sum += num;break;case 1:o_ct++;o_sum += num;break;}printf("Enter next integer:(0 to quit).\n");}printf("%d even entered.", e_ct);if (e_ct > 0)printf(" Average is %g.", e_sum / e_ct);putchar('\n');printf("%d odd entered.", o_ct);if (o_ct > 0)printf(" Average is %g.", o_sum / o_ct);putchar('\n');printf("Done!\n");return 0;}/* programming exercise 7-6 */#include <stdio.h>int main(void){char ch;char prev = 0;/* 记得对prev进行0填充,否则有可能定义的内存的垃圾数据恰好为e */int count = 0;while ((ch = getchar()) != '#'){if (ch == 'i' && prev == 'e')count++;prev = ch;}switch (count){case 0:printf("\"ei\" no apeared.\n");break;case 1:printf("\"ei\" apeared 1 time.\n");break;default:printf("\"ei\" apeared %d times", count);}return 0;}/* programming exercise 7-7 */#include <stdio.h>#define BASEPAY 10#define BASEHRS 40#define OVERRATE 1.5#define LEVEL1 300#define LEVEL2 150#define TAX1 0.15#define TAX2 0.20#define TAX3 0.25int main(void){float hours;float total, tax, net;printf("Please enter your work time: ");scanf("%f", &hours);if (hours > BASEHRS)total = BASEPAY * (BASEHRS + (hours - BASEHRS) * OVERRATE);elsetotal = hours * BASEPAY;if (total <= LEVEL1)tax = total * TAX1;else if (total <= (LEVEL1 + LEVEL2))tax = LEVEL1 * TAX1 + (total - LEVEL1) * TAX2;elsetax = LEVEL1 * TAX1 + LEVEL2 * TAX2 + (total - LEVEL1 - LEVEL2) * TAX3;net = total - tax;printf("total = %g, tax = %g, net = %g.\n",total, tax, net);return 0;}/* programming exercise 7-8 */#include <stdio.h>#define BASEHRS 40#define OVERRATE 1.5#define T_LEVEL1 300#define T_LEVEL2 150#define S_LEVEL1 8.75#define S_LEVEL2 9.33#define S_LEVEL3 10.00#define S_LEVEL4 11.20#define TAX1 0.15#define TAX2 0.20#define TAX3 0.25int main(void){float hours;float basepay;float total, tax, net;int choice;printf("****************************************************** ***********\n");printf("Enter the number corresponding to the desired payrate or action:\n");printf("1)$8.75/hr 2)$9.33/hr\n");printf("3)$10.00/hr 4)$11.20/hr\n");printf("5)quit\n");printf("****************************************************** ***********\n");while (scanf("%d", &choice) == 1 && choice != 5){switch(choice){case 1:basepay = S_LEVEL1;break;case 2:basepay = S_LEVEL2;break;case 3:basepay = S_LEVEL3;break;case 4:basepay = S_LEVEL4;break;default:printf("You should enter the number between 1 to 4 (5 to quit).\n");printf("Please enter the right number: \n");continue;}printf("Please enter your work time: ");scanf("%f", &hours);if (hours > BASEHRS)total = basepay * (BASEHRS + (hours - BASEHRS) * OVERRATE);elsetotal = hours * basepay;if (total <= T_LEVEL1)tax = total * TAX1;else if (total <= (T_LEVEL1 + T_LEVEL2))tax = T_LEVEL1 * TAX1 + (total - T_LEVEL1) * TAX2;elsetax = T_LEVEL1 * TAX1 + T_LEVEL2 * TAX2 + (total - T_LEVEL1 - T_LEVEL2) * TAX3;net = total - tax;printf("total = %g, tax = %g, net = %g.\n",total, tax, net);printf("Please enter next number:\n");}printf("That's all!\n");return 0;}/* programmming exercise 7-9 */#include <stdio.h>int main(void){int num;int div;int count;printf("Please enter the limit in integer:\n");scanf("%d", &num);while (num >1){for (div = 2, count = 0; div <= num / 2; div++){if(num % div == 0)count++;}if (count == 0)printf("%d ", num);num--;}printf("\nThat's all!\n");return 0;}/* programming exercise 7-10 */#include <stdio.h>#define RATE1 0.15#define RATE2 0.28#define LEVEL1 17850#define LEVEL2 23900#define LEVEL3 29750#define LEVEL4 14875int main(void){double tax;double income;int type;long level;printf("Please choose your type as follow:(q to quit)\n");printf("1)Single; 2)Householder;\n");printf("3)Married; 4)Divorced\n");while (scanf("%d", &type) == 1){switch (type){case 1:level = LEVEL1;break;case 2:level = LEVEL2;break;case 3:level = LEVEL3;break;case 4:level = LEVEL4;break;default:printf("You should choose the number""between 2 and 4(q to quit).\n");printf("Please enter the right number:\n");continue;}printf("Please enter your income:\n");scanf("%lf", &income);if (income <= level)tax = income * RATE1;elsetax = level * RATE1 + (income - level) * RATE2;printf("Your taxes is %g.\n", tax);printf("Please enter next type in integer:(q to quit)\n");}printf("That's all!\n");return 0;}/* programming exercise 7-11 */ #include <stdio.h>#include <stdbool.h>#define WT_LEVEL1 5#define WT_LEVEL2 20#define FR_LEVEL1 3.5#define FR_LEVEL2 10#define FR_LEVEL3 8#define FR_OVER 0.1#define DISCOUNT 0.05#define AC_PRC 1.25#define BT_PRC 0.65#define CR_PRC 0.89int main(void){char a, b, c;char ch;float a_wt = 0, b_wt = 0, c_wt = 0;float total_wt;float cost, total_cost, freight;int discount = 0;printf("************************************************\n");printf("Please choose the vegatable and weight you want:\n");printf("(type as follow, q to quit)\n");printf("a) artichoke; b) beet; c) carrot;\n");printf("************************************************\n");while ((ch = getchar()) != 'q'){switch (ch){case 'a':printf("You select artichoke, enter the weight:\n");scanf("%f", &a_wt);break;case 'b':printf("You select beet, enter the weight:\n");scanf("%f", &b_wt);break;case 'c':printf("You select carrot, enter the weight:\n");scanf("%f", &c_wt);break;default:printf("Please enter a, b, or c:\n");continue;}printf("Other vegatable?\n");}printf("\n%g %s artichoke, %g %s beet, %g %s carrot.\n", a_wt, a_wt > 1 ? "pounds" : "pound",b_wt, b_wt > 1 ? "pounds" : "pound",c_wt, c_wt > 1 ? "pounds" : "pound");total_wt = a_wt + b_wt + c_wt;cost = a_wt * AC_PRC + b_wt * BT_PRC + c_wt * CR_PRC;if (cost >= 100){cost *= (1 - DISCOUNT);discount++;}if (total_wt == 0)freight = 0;else if (total_wt <= 5)freight = FR_LEVEL1;else if (total_wt < 20)freight = FR_LEVEL2;elsefreight = FR_LEVEL3 + total_wt * FR_OVER;total_cost = cost + freight;printf("Average cost is $%g per pound, tatol weight is %g %s,\n" ,total_cost / total_wt, total_wt, total_wt > 1 ? "pounds" : "pound");printf("total cost is $%g, and %d%% off, freight is $%g.\n", total_cost, discount == 1 ? 5 : 0, freight);return 0;}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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*/ 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> void jolly(void);void deny(void); int main(void) { jolly(); jolly(); jolly(); deny();return 0; }void jolly(void){printf("For he's a jolly good fellow!\n");}void deny(void){printf("Which nobody can deny!\n");}PE 2---6/* Programming Exercise 2-6 */ #include <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> void one_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—2/* Programming Exercise 3-2 */ #include <stdio.h> int main(void){int ascii;printf("Enter an ASCII code: "); scanf("%d", &ascii);printf("%d is the ASCII code for %c.\n", ascii, ascii); return 0;}PE 3—4/* Programming Exercise 3-4 */ #include <stdio.h> int main(void){ floatnum;printf("Enter a floating-point value: "); scanf("%f", &num);printf("fixed-point notation: %f\n", num); printf("exponentialnotation: %e\n", num); printf("p notation: %a\n", num); return 0; }PE 3—6/* Programming Exercise 3-6 */ #include <stdio.h> int main(void){float mass_mol = 3.0e-23; /* mass of water molecule in grams */ float mass_qt = 950; /* mass of quart of water in grams */ float quarts; float molecules;printf("Enter the number of quarts of water: "); scanf("%f", &quarts);molecules = quarts * mass_qt / mass_mol;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> int main(void){ char fname[40]; char lname[40];printf("Enter your first name: "); scanf("%s", fname); printf("Enter your last name: "); scanf("%s", lname); printf("%s, %s\n", lname, fname); return 0;}PE 4-- _4/* Programming Exercise 4-4 */ #include <stdio.h> int main(void){ float height;char name[40];printf("Enter your height in inches: "); scanf("%f", &height); printf("Enter your name: "); scanf("%s", name);printf("%s, you are %.3f feet tall\n", name, height / 12.0);return 0;}PE 4-- _7/* Programming Exercise 4-7 */ #include <stdio.h> #include <float.h> int main(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 ExercisesPE 5—1/* Programming Exercise 5-1 */ #include <stdio.h> int main(void){ const int minperhour =60; int minutes, hours,mins;printf("Enter the number of minutes to convert: "); scanf("%d", &minutes); while (minutes > 0 ){ hours = minutes / minperhour; mins = minutes % minperhour;printf("%d minutes = %d hours, %d minutes\n", minutes, hours, mins); printf("Enter next minutes value (0 to quit): "); scanf("%d", &minutes);}printf("Bye\n");return 0;}PE 5—3/* Programming Exercise 5-3 */#include <stdio.h> int main(void){ const int daysperweek =7; int days, weeks, day_rem;printf("Enter the number of days: ");scanf("%d", &days); while (days > 0){ weeks = days /daysperweek; day_rem = days % daysperweek;printf("%d days are %d weeks and %d days.\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 upper limit: "); scanf("%d", &n); count = 0; sum = 0; while (count++ < n) sum = sum + count; printf("sum = %d\n", sum); return 0;}PE 5—7/* Programming Exercise 5-7 */#include <stdio.h> void showCube(double x);int main(void) /* finds cube of entered number */{ doubleval;printf("Enter a floating-point value: "); 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 SIZE26 int main( 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> int main( void ) { char let = 'F'; char start; char end;for (end = let; end >= 'A'; end--){for (start = let; start >= end; start--) printf("%c", start); printf("\n");} return 0;}PE 6—6/* pe6-6.c */ #include <stdio.h> int main( void ) { int lower, upper, index; int square, cube;printf("Enter starting integer: "); scanf("%d", &lower); printf("Enter endinginteger: "); 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);} return 0;}PE 6—8/* pe6-8.c */ #include <stdio.h> int main( void ) { double n, m; double res;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> #define SIZE 8 int main( void ){ int vals[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>#define SIZE 8 int main( void ){int twopows[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> #define SIZE 8 int main(void){ double arr[SIZE]; double arr_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 #define RATE_COMP 0.05 #define INIT_AMT 100.0 int main( void ){double daphne = INIT_AMT; double deidre = INIT_AMT; int years = 0;while (deidre <= daphne){ daphne += RATE_SIMP *INIT_AMT; deidre += RATE_COMP * deidre;++years; } printf("Investment values after %d years:\n", years);printf("Daphne: $%.2f\n", daphne); printf("Deidre: $%.2f\n", deidre); return 0;}Chapter 7 Programming ExercisesPE 7---1/* Programming Exercise 7-1 */ #include <stdio.h> int main(void){ char ch;int sp_ct = 0;int nl_ct = 0;int other = 0; while ((ch = getchar()) != '#'){ if (ch == ' ') sp_ct++; else if (ch == '\n') nl_ct++; else other++;}printf("spaces: %d, newlines: %d, others: %d\n", sp_ct, nl_ct, other);return 0;}PE 7---3/* Programming Exercise 7-3 */#include <stdio.h> int main(void){ int n; double sumeven = 0.0; int ct_even = 0; double sumodd = 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");return 0;}PE 7-- -5/* Programming Exercise 7-5 */ #include <stdio.h> int main(void){ char ch; int ct1 = 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);return 0;}PE 7---7// Programming Exercise 7-7 #include <stdio.h>#define BASEPAY #define BASEHRS #define OVERTIME #define AMT1 300#define AMT2 150#define RATE1 0.15#define RATE2 0.20#define RATE3 0.25main(void) {// $10 per hour// hours at basepay// 1.5 time// 1st rate tier// 2st rate tier// rate for 1st tier// rate for 2nd tier// rate for 3rd tier int10401.5double hours;double gross; double net; double taxes;printf("Enter the number of hours worked this week: "); 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);return 0;}PE 7-- -9/* Programming Exercise 7-9 */ #include <stdio.h> #include <stdbool.h> int main(void) {int limit;int num; intdiv;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> int main(void) {const double price_artichokes = 2.05;const double price_beets = 1.15;const double price_carrots = 1.09;const double DISCOUNT_RATE = 0.05; const double under5 = 6.50; constdouble under20 = 14.00; const double base20 = 14.00; const double extralb = 0.50;char ch;double lb_artichokes = 0; double lb_beets = 0; double lb_carrots = 0; double lb_temp; double lb_total;double cost_artichokes; double cost_beets; double cost_carrots; double cost_total; double final_total; double discount; double shipping;printf("Enter a to buy artichokes, b for beets, "); printf("c for carrots, q to quit: "); while ((ch = getchar()) != 'q' && ch != '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; else shipping = 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("%.2f lbs of beets at $%.2f per pound: $%.2f\n", lb_beets, price_beets, cost_beets); printf("%.2f lbs 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("Volume 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);return 0;}PE 8—3/* Programming Exercise 8-3 *//* Using ctype.h eliminates need to assume consecutive coding */ #include <stdio.h> #include <ctype.h> int main(void) { int ch; unsigned long uct = 0; unsigned long lct = 0; unsigned long oct = 0;while ((ch = getchar()) != EOF) if (isupper(ch)) uct++; else if (islower(ch)) lct++; else oct++;printf("%lu uppercase characters read\n", uct);printf("%lu lowercase characters read\n", lct); printf("%lu other characters read\n", oct); return 0;}/* or you could use if(ch >= 'A' && ch <= 'Z') uct++;else if (ch >= 'a' && ch <= 'z') lct++; else oct++;*/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> int main(void) { int high = 100; int low = 1; int guess = (high + low) / 2; char response;printf("Pick an integer from 1 to 100. I will try to guess "); printf("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> double net;double taxes; double pay; char response;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 this week: "); scanf("%lf", &hours); if(hours <= BASEHRS) gross = hours * pay; else#define BASEPAY1 #define BASEPAY2 #define BASEPAY3 #define BASEPAY4 #define BASEHRS #define OVERTIME #define AMT1 #define AMT2 #define RATE1 #define RATE2 #define RATE3 int getfirst(void);main(void) 8.75 // $8.75 per hour9.33 // $9.33 per hour10.00 // $10.00 per hour11.20 // $11.20 per hour40 // hours at basepay 1.5// 1.5 time// 1st rate tier // 2st rate tier // rate for 1st tier // rate for 2nd tier // rate for 3rd tier 300 150 0.15 0.20 0.25 void menu(void); int { double hours;double gross;gross = 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");return 0;}void menu(void)********************************************************11printf("Enter the letter corresponding to the desired pay rate" " 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"); ********************************************************11}int getfirst(void){ int ch;ch = getchar();while (isspace(ch))ch = getchar(); while (getchar() != '\n') continue; return ch;}Chapter 9 Programming ExercisesPE 9—1/* Programming Exercise 9-1 */#include <stdio.h>double min(double, double); int main(void){double x, y; printf("Enter two numbers (q to quit): "); while (scanf("%lf %lf", &x, &y) == 2){ printf("The smaller number is %f.\n", min(x,y)); printf("Next two values (q to quit): ");} printf("Bye!\n");return 0;}double min(double a, double b) {return a < b ? a : b;}/* alternative implementation double min(double a, double b){ if (a < b) return a; else return 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("II******* **\n");printf("II*********\n");printf("Bye!\n");return 0;}// start rows and cols at 0 void chLineRow(char ch, int c, 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("Enter two 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");return 0;}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); /* ANSI prototype */ int main(void) { double x, xpow; int n; printf("Enter a number and the integer power"); printf(" to which\nthe number will be 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 numbers or q to quit.\n");} printf("Hope you enjoyed this power trip -- bye!\n"); return 0;} double power(double a, int b) /* function definition*/{ double pow =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> void to_base_n(int x, int base);int main(void) { int number; int b;int count; printf("Enter an integer (q to quit):\n"); while (scanf("%d", &number) == 1) { printf("Enter number base (2-10):"); while ((count = scanf("%d",&b))== 1&& (b < 2 || b > 10)){printf("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 of months 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; float subtot,total;printf(" YEAR RAINFALL (inches)\n");for (year = 0, total = 0; year < YRS; year++){ /* for each year, sum rainfall for each month */ 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 AVERAGES:\n\n");printf(" Jan Feb Mar Apr May Jun Jul Aug Sep Oct "); printf(" Nov Dec\n");for (month = 0; month < MONTHS; month++){ /* for each month, sum rainfall over years */ 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(const int 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);return 0;}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');}PE 10-- -5/* Programming Exercise 10-5 */#include <stdio.h>#define LEN 10 double max_diff(const double ar[], int n); void show_arr(const double ar[], int n);int main(void){double orig[LEN] = {1.1,2,3,4,12,61.3,7,8,9,10}; double max;show_arr(orig, LEN); max = max_diff(orig, LEN);printf("%g = maximum difference\n", max);return 0;} double max_diff(const double ar[], int n) { int i; double max = ar[0]; double min =ar[0];for (i = 1; i < n; i++){ if (max < ar[i]) max = ar[i]; else if (min > ar[i]) min = ar[i];}return max - min;}void show_arr(const double ar[], int n){ int i; for (i = 0; i < n; i++) printf("%g ", ar[i]);putchar('\n');}PE 10---8/* Programming Exercise 10-8 */#include <stdio.h>#define LEN1 7#define LEN2 3void copy_arr(int ar1[], const int ar2[], int n); void show_arr(const int [], int);int main(void){int orig[LEN1] = {1,2,3,4,5,6,7};int copy[LEN2];show_arr(orig, LEN1); copy_arr(copy, orig + 2, LEN2);show_arr(copy, LEN2);return 0;}void copy_arr(int ar1[], const int ar2[], int n){ int i; for(i = 0; i < n; i++)ar1[i] = ar2[i];。