Cprimerplus编程练习答案

合集下载

cprimer plus第版编程练习答案已

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 primer plus (第6版) 中文版编程练习答案

C    primer plus (第6版) 中文版编程练习答案
cout<<"First,enter your height of feet part(输入你身高的英尺部分):_\b";
int ht_feet;
cin>>ht_feet;
cout<<"Second,enter your height of inch part(输入你身高的英寸部分):_\b";
int ht_inch;
return 0;
}
double C2F(double t)
{
return 1.8*t+32;
}
//ex2.6---convert the light years valve to astronomical units--把光年转换为天文单位
#include<iostream>
double convert(double);//函数原型
cin>>world_population;
cout<<"Enter the population of the US:";
long long US_population;
cin>>US_population;
double percentage;
percentage=(double)US_population/world_population*100;
int main()
{
using namespace std;
cout<<"Enter the number of light years:";
double light_years;
cin>>light_years;

c++primerplus课后编程练习答案

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编程习题答案

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++primerplus(第六版)课后编程练习答案培训资料

c++primerplus(第六版)课后编程练习答案培训资料

c + + p r i me r p l u s (第六版)课后编程练习答案〃ex2.1--display your n ame and address #in clude<iostream>int main(v oid){using n amespace std;cout<<"My n ame is liao chu ngua ng and I live in hunan che nzhou.\”〃ex2.2--convert the furlong units to yard uints扌把浪单位换位码单位#include<iostream>double fur2yd(double);int main(){using n amespace std;cout<<"e nter the dista nee measured by furl ong un its:"; double fur;cin»fur;cout<<"c onvert the furlo ng to yard"<<e ndl;double yd;yd=fur2yd(fur);coutvvfurvv" furlong is "<<yd<<" yard"<<e ndl;return 0;}double fur2yd(double t){return 220*t;}〃ex2.3-每个函数都被调用两次#in clude<iostream>void mice();void see();using n amespace std;int main(){mice();mice();see();see();return 0;}void mice(){cout«"three bli nd mice"«e ndl;}void see(){cout<<"see how they run"<<en dl;}〃ex2.4#in clude<iostream>int mai n(){using n amespace std;cout<<"E nter your age:";int age;cin> >age;in t mon th;mon th=age*12;coutvvagevv" years is "<<mon th<<" mon ths"<<e ndl;return 0;}〃ex2.5---convert the Celsius valve to Fahre nheit value#in clude<iostream>double C2F(double);int main(){using n amespace std;cout«"please en ter a Celsius value:";double C;cin> >C;double F;F=C2F(C);coutvvCvv" degrees Celsius is "<<F<<" degrees Fahre nheit."«e ndl; return 0; }double C2F(double t){return 1.8*t+32;}〃ex2.6---convert the light years valve to astronomical units-把光年转换为天文单位#in clude<iostream>double conv ert(double);//函数原型int main(){using n amespace std;cout<<"E nter the nu mber of light years:";double light_years;cin> >light_years;double astro_ un its;astro_ un its=co nv ert(light_years);cout<<light_years<<" light_years = "<<astro_u ni ts<<" astr ono mical un its."v<e ndl; return 0;}double conv ert(double t){return 63240*t;//1 光年=63240 天文单位}〃ex2.7--显示用户输入的小时数和分钟数#in clude<iostream>void show();mai n(){using n amespace std;show();return 0;}void show(){using n amespace std;int h,m;cout<<"e nter the nu mber of hours:"; cin> >h;cout<<"e nter the nu mber of minu tes:";cin>>m; coutvv"Time:"v<hvv":"vvmvve ndl;〃ex3.1—将身高用英尺(feet)和英寸(inch)表示#in clude<iostream> const int in ch_per_feet=12;〃cons常量--1feet=12i nches--1 英尺=12 英寸int main() {using n amespace std;cout<<"please en ter your height in inches: __ \b\b\b";〃\b表示为退格字符intht_in ch;cin> >ht_i nch;int ht_feet=ht_i nch/i nch_per_feet;//取商int rm_i nch=ht_i nch%i nch_per_feet;〃取余cout<<"your height is "<<ht_feet<<" feet,a nd " <<rm_i nch<< "in ches\n";return 0;}//ex3.2--计算相应的body mass index (体重指数)#in clude<iostream>const int in ch_per_feet=12;const double meter_per_i nch=0.0254;const double poun d_per_kilogram=2.2;int main(){using n amespace std;cout<<"Please en ter your height:"<<e ndl;cout«"First,enter your height of feet part (输入你身高的英尺部分):_\b";int ht_feet;cin> >ht_feet;cout«"Seco nd,e nter your height of inch part (输入你身高的英寸部分):_\b";int ht_in ch;cin> >ht_i nch;cout«"Now,please en ter your weight in pound: __ \b\b\b";double wt_po und;cin> >wt_po und;int in ch;in ch=ht_feet*i nch_per_feet+ht_i nch;double ht_meter;ht_meter=i nch*meter_per_i nch;double wt_kilogram;wt_kilogram=wt_po un d/po un d_per_kilogram; cout«e ndl;cout<<"Your pensonal body in formatio n as follows:"<<e ndl;cout«"身高:"<<inch<<"(英尺inch)\n"<<"身高:"<<ht_meter<<"(米meter)\n"<<"体重:"<<wt_kilogram<<"(千克kilogram八n";double BMI;BMI=wt_kilogram/(ht_meter*ht_meter);cout<<"your Body Mass In dex(体重指数)is "<<BMI<<e ndl;return 0;}〃ex3.3以度,分,秒输入,以度输出#in clude<iostream>const int minu tes_per_degree=60;const int sec on ds_per_m inu te=60;int main(){using n amespace std;cout<<"E nter a latitude in degrees, minu tes,a nd sec on ds:\n"; cout<<"First,e nter the degrees:";int degree;cin> >degree;cout<<"Next,e nter the minu tes of arc:";int min ute;cin»minu te;cout«"Fia nlly,e nter the sec onds of arc:";int sec ond;cin> >sec ond;double show_i n_degree;show_in_degree=(double)degree+(double)mi nute/mi nutes_per_degree+(doubl e)seco nd/mi nu tes_per_degree/sec on ds_per_mi nu te;cout<<degree<<" degrees,"<< minu te<<" minu tes,"<<sec on d<<"sec onds ="<<show_i n_degree<<" degrees\n";return 0;}//ex3.4#in clude<iostream>const int hours_per_day=24;const int minu tes_per_hour=60;const int sec on ds_per_m inu te=60;int main(){using n amespace std;cout<<"E nter the nu mber of sec on ds:";long sec on ds;cin> >sec on ds;int Day,Hour,M inu te,Sec ond;Day=sec on ds/sec on ds_per_mi nute/mi nu tes_per_hour/hours_per_day;Hour=sec on ds/sec on ds_per_mi nute/mi nu tes_per_hour%hours_per_day;Min ute=seco nds/seco nds_per_mi nute%mi nu tes_per_hour;Secon d=sec on ds%sec on ds_per_m inu te;cout«sec on ds<<"sec onds = "<<Day<<" days,"<<Hour<<"hours,"<< Minu te<<" minu tes,"<<Sec on d<<" sec onds\n";return 0;}〃ex3.5#in clude<iostream>int mai n(){using n amespace std;cout<<"E nter the world populati on:";long long world_populati on;cin> >world_populati on;cout<<"E nter the populati on of the US:";long long US_populati on;cin»U S_populati on;double perce ntage;perce ntage=(double)US_populati on/world_populati on *100;cout<<"The population of the US is "<<percentage<<"% of the world population.\n"; return 0;}〃ex3.6汽车耗油量-美国(mpg)or欧洲风格(L/100Km)#in clude<iostream> int main(){using n amespace std;cout«"E nter the miles of dista nee you have drive n:";double m_dista nee;cin>> m_dista nee;cout<<"E nter the gallo ns of gasoli ne you have used:";double m_gasoli ne;cin>> m_gasoli ne;cout<<"Your car can run "<<m_dista nce/m_gasoli ne<<" miles per gallo n\n";cout«"Computi ng by Europea n style:\n";cout<<"Enter the distance in kilometers:";double k_dista nce;cin>> k_dista nce;cout<<"E nter the petrol in liters:";double k_gasoli ne;cin>> k_gasoli ne;cout<<"I n Europea n style:"«"your can used "<<100*k_gasoli ne/k_dista nce<<" liters of petrol per 100 kilometers\n";return 0;}//ex3.7 automobile gaso line con sumption 耗油量--欧洲风格(L/100Km)转换成美国风格(mpg)#in clude<iostream>int main(){using n amespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"Europea n style(liters per 100 kilometers):";double Euro_style;cin> >Euro_style;cout<<"C onv erts to U.S. style(miles per gallo n):"«e ndl;coutv<Euro_stylevv" L/100Km = "v<62.14*3.875/Euro_style<v" mpg\n"; return 0; }// Note that 100 kilometers is 62.14 miles, and 1 gallon is 3.875 liters.//Thus, 19 mpg is about 12.4 L/100Km, and 27 mpg is about 8.7 L/100Km.Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):12.4Conv erts to U.S. style(miles per gallo n):12.4 L/100Km = 19.4187 mpgPress any key to con ti nue // ex3.7 automobile gasol ine con sumption耗油量--美国风格(mpg )转换成欧洲风格(L/100Km)#in clude<iostream>int main(){using n amespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"U.S. style(miles per gallo n):";double US_style;cin >>US_style;cout<<"C onv erts to Europea n style(miles per gall on ):"<<e ndl;cout<<US_style<<" mpg = "<< 62.14*3.875/US_style<<"L/100Km\n"; return 0; }// Enter the automobile gasoline consumption figure inU.S. style(miles per gallo n) :19Conv erts to Europea n style(miles per gallo n):19 mpg = 12.6733L/100KmPress any key to con ti nue//ex4.1 display the information of student #in clude<iostream>const int Asize=20;using n amespace std;struct stude nt/定义结构描述{char first name[Asize]; char last name[Asize]; char grade;int age;};void display(stude nt);〃函数原型放在结构描述后int main(){cout«"what is your first n ame?"<<e ndl;stude nt leg;//创建结构变量(结构数据对象)cin .getli ne(lcg.first name,Asize); cout<<"what is your last n ame?"<<e ndl;cin .getli ne(lcg .l ast name,Asize);cout<<"what letter grade do you deserve?"<<e ndl;cin> >lcg.grade;cout<<"what is your age?"<<e ndl;cin> >lcg.age;display(lcg);return 0;}void display(stude nt n ame){cout«"Name: " <<n ame.first name<<","< <n ame .l ast name«e ndl;cout<v"Grade:"vvchar( name.grade+1)«e ndl;cout<<"Age:"< <n ame.age<<e ndl;} //ex4.2 use the stri ng-class in stead of char-array #in clude<iostream>#in clude<stri ng>int main(){using n amespace std;stri ng n ame,dessert;cout<<"E nter your n ame: \n";getl in e(ci n,n ame);cout<<"E nter your favorite dessert: \n"; getli ne(ci n, dessert);cout<<"I have some delicious "<<dessert; cout«" for you, "< <n ame<<".\n";return 0;〃有时候会遇到需要按下两次回车键才能正确的显示结果,这是VC++6.0的一个BUG,更改如下:else if (_Tr::eq((_E)_C, _D)){_Chg = true;_I .rdbuf()->sbumpc(); 〃修改后的break; }ex4.3输入其名和姓,并组合显示#in clude<iostream>#in clude<cstri ng>const int Asize=20;int main(){using n amespace std;char fn ame[Asize];char In ame[Asize];char full name[2*Asize+1];cout<<"Enter your first name:";//输入名字,存储在fname[]数组中cin .getli ne(fname,Asize);cout<<"Enter your last name:";//输入姓,存储在Iname[]数组中cin .getli ne(l name,Asize);strncpy(full name,l name,Asize);〃把姓ln ame 复制到full name 空数组中strcat(full name,",");// 把“,”附加到上述full name 尾部strn cat(full name,fname,Asize);//把fname 名字附加至U 上述full name 尾部fullname[2*Asize ]='\0';//为防止字符型数组溢出,在数组结尾添加结束符cout<<"Here's the information in a single string:"<<fullname<<endl;//显示组合结果return 0;} //ex4.4使用string对象存储、显示组合结果#in clude<iostream>#in cludevstri ng>int main(){using n amespace std;stri ng fname ,ln ame,attach,full name; cout<<"E nter your first n ame:";getline(cin,fname);//note将一行输入读取到string类对象中使用的是getli ne(ci n, str)//它没有使用句点表示法,所以不是类方法cout<<"E nter your last n ame:";getli ne(ci n,ln ame);attach=",";full name=In ame+attach+f name;cout<<"Here's the information in a single string:"<<fullname<<endl; return 0;}〃ex4.5 declare a struct and in itialize it 声明结果并创建一个变量#in clude<iostream> const int Asize=20; struct Can dyBar{char bran d[Asize];double weight;int calory;};int main(){using n amespace std;Ca ndyBar sn ack={"Mocha Mun ch",2.3,350}; cout<<"Here's the information of snack:\n"; cout<<"bra nd:"<<s nack.bra nd<<e ndl; 8山<<妝6:9“:"<<$ nack.weight<<e ndl; coutvv"calory:"vvs nack.calory<<e ndl; return 0; } //ex4.6结构数组的声明及初始化#in clude<iostream> const int Asize=20;struct Can dyBar{char bran d[Asize];double weight;int calory;};int main(){using n amespace std;Ca ndyBar sn ack[3]={ {"Mocha Mun ch",2.3,350}, {"XuFuJi",1.1,300},{"Alps",0.4,100}};for(int i=0;i<3;i++)〃利用for循环来显示snack变量的内容{cout«s nack[i].bra nd<<e ndl<<s nack[i].weight<<e ndl<<s nack[i].calory«e ndl«e ndl;}return 0;}〃ex4.7 pizza 披萨饼#in clude<iostream> #in clude<stri ng> const int Size=20;struct pizza//声明结构{char compa ny [Size]; double diameter; double weight;};int main(){using n amespace std;pizza pie;//创建一个名为pie的结构变量cout<<"What's the n ame of pizzacompa ny:"; cin. getl in e(pa ny ,Size); cout«"What's the diameter ofpizza:";cin> >pie.diameter; cout<<"What's the weight of pizza:";cin> >pie.weight;cout<<"compa ny:"«pa ny«en dl; cout<v"diameter:"vvpie.diameter<v"i nches"«e ndl; cout<v"weight:"vvpie.weight<v"o un ches"<<e ndl; return 0;}〃ex4.8 pizza pie披萨饼使用new创建动态结构#in clude<iostream>#in clude<stri ng>const int Size=20;struct pizza//声明结构{char compa ny [Size];double diameter;double weight;};int main(){using n amespace std;pizza *pie=new pizza;//使用new 仓U建动态结构cout<<"What's the diameter of pizza:";cin> >pie->diameter;cin. get();//读取下一个字符cout<<"What's the n ame of pizza compa ny:";cin .get(pie->compa ny,Size); cout<<"What's the weight of pizza:";cin> >pie->weight; cout<v"diameter:"vvpie->diameter< <" in ches"<<e ndl;cout<<"compa ny:"«pie->compa ny«en dl; cout<v"weight:"vvpie->weight<v" oun ches"<<e ndl;delete pie;//delete释放内存return 0;〃ex.4.9使用new动态分配数组一方法1#in clude<iostream>#in clude<stri ng>using n amespace std;struct Can dyBar{stri ng brand;double weight;int calory;};int main(){Can dyBar *sn ack= new Can dyBar[3];snack[0].brand="A";〃单个初始化由new动态分配的内存sn ack[0].weight=1.1; sn ack[0].calory=200; sn ack[1].bra nd="B";sn ack[1].weight=2.2; sn ack[1].calory=400; sn ack[2].bra nd="C";sn ack[2].weight=4.4;sn ack[2].calory=500;for(int i=0;i<3;i++){cout << " bran d: " << sn ack[i].bra nd << en dl;cout << " weight: " << sn ack[i].weight << en dl;cout << " calorie: " << sn ack[i].calory << en dl<<e ndl; }delete [] sn ack;return 0;} //ex.4.10数组一方法1#i nclude <iostream> int main(){using n amespace std;const int Size = 3;int success[Size];cout<<"E nter your success of the three times 40 meters runnin g:\n"; cin >> success[0]»success[1]»success[2];cout<v"success1:"v<success[0]vve ndl;cout<v"success2:"vvsuccess[1]v<e ndl;cout<v"success3:"v<success[2]vve ndl;double average=(success[0]+success[1]+success[2])/3;cout<<"average:"<<average<<e ndl;return 0;}//ex.4.10 array—方法2#i nclude <iostream>#in clude <array>int main(){using n amespace std;array<double,4>ad={0};cout<<"E nter your success of the three times 40 meters runnin g:\n"; cin >> ad[0]»ad[1]»ad[2];cout<v"success1:"v<ad[0]vve ndl;cout<v"success2:"vvad[1]v<e ndl;cout<v"success3:"v<ad[2]vve ndl;ad[3]=(ad[0]+ad[1]+ad[2])/3;cout<<"average:"<<ad[3]<<e ndl;return 0;}//ex.5.1#in clude <iostream> int mai n(){using n amespace std;cout<<"Please en ter two in tegers:" int n um1, num2;cin»n um1> >n um2;int sum=O;for(i nt temp=n um1;temp<=n um2;++temp)//or temp++sum+=temp;cout<<"The sum from "<<n um1<<" to "<<n um2<<" is "<<sum<<e ndl; return 0; }//ex.5.2#in clude <iostream>#in clude<array>int mai n(){using n amespace std;array vlong double,101>ad={0};ad[1]=ad[0]=1L;for(int i=2;i<101;i++)ad[i]=i*ad[i-1];for(int i=0;i<101;i++)coutvvivv"! = "v<ad[i]v<e ndl;return 0;}〃ex.5.3#in clude <iostream>int mai n(){using n amespace std;cout<<"Please en ter an in teger:";int sum=0,n um;while((ci n»num)&&n um!=0){sum+=n um;cout<<"So far, the sum is "v<sumv<e ndl; cout<<"Please en ter an in teger:";}return 0;}//ex.5.4 #in clude <iostream>int main(){using n amespace std;double sum1,sum2;sum仁sum2=0.0;int year=0;while(sum2<=sum1){++year;sum1+=10;sum2=(100+sum2)*0.05+sum2;}coutvv"经过"vvyearvv"年后,Cleo的投资价值才能超过Daphne的投资价值。

cprimerplus习题答案

cprimerplus习题答案

cprimerplus习题答案cprimerplus习题答案C Primer Plus是一本经典的C语言教材,被广泛用于学习和教授C语言的人士。

这本书的习题是帮助读者巩固所学知识和提高编程能力的重要环节。

在这篇文章中,我将为大家提供一些C Primer Plus习题的答案,希望对正在学习C语言的读者有所帮助。

1. 习题1:编写一个程序,输出"Hello, World!"。

答案:```c#include <stdio.h>int main() {printf("Hello, World!");return 0;}```这是一个非常简单的程序,使用了C语言的标准库函数printf()来输出字符串。

2. 习题2:编写一个程序,输入两个整数,然后计算它们的和并输出。

答案:```c#include <stdio.h>int main() {int num1, num2, sum;printf("请输入两个整数:");scanf("%d %d", &num1, &num2);sum = num1 + num2;printf("它们的和是:%d", sum);return 0;}```这个程序使用了scanf()函数来接收用户输入的两个整数,并使用加法运算符计算它们的和,最后使用printf()函数输出结果。

3. 习题3:编写一个程序,输入一个整数,然后判断它是否为偶数并输出结果。

答案:```c#include <stdio.h>int main() {int num;printf("请输入一个整数:");scanf("%d", &num);if (num % 2 == 0) {printf("这是一个偶数。

C++-primer-plus中文版-编程练习答案

C++-primer-plus中文版-编程练习答案

第二章:开始学习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): Convertsto . style(miles per gallon):L/100Km = mpgPress any key to continuestyle(miles per gallon):"; doubleUS_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 << e ndl;cout << " calorie: " << snack[i].calory << endl<<endl;}delete [] snack;return 0;}et(); car* ps=newcar[num];for(int i=0;i<num;++i){cout<<"Car #"<<i+1<<":\n"; c out<<"Pleaseenter the make: "; g etline(cin,ps[i].name);cout<<"Please enter the year made: ";(cin>>ps[i].year).get();}cout<<"Here is your collection:\n"; f or(inti=0;i<num;++i) c out<<ps[i].year<<""<<ps[i].name<<endl; delete [] ps;return 0;}#include <iostream>#include <string> usingnamespace std; struct car{string maker; int year; };int main(){int number;cout << "How many cars do you wish to catalog "; cin >> number;car* a = new car[number];for (int i = 0; i < number; i++){cout << "Car #" << i+1 << ": " << endl; cout << "Please enterthe maker: "; ();getline(cin,a[i].maker);cout << "Please enter the year made: "; cin >> a[i].year;}cout << "Here is your collection: " << endl; for (int i = 0; i < number;i++)cout << a[i].year << " " << a[i].maker <<endl; delete [] a;return 0;}#include <iostream> usingnamespace std; struct car{char maker[20]; intyear;};int main(){int number;cout << "How many cars do you wish to catalog "; cin >> number;car* a = new car[number];for (int i = 0; i < number; i++){cout << "Car #" << i+1 << ": " << endl; cout << "Please enterthe maker: "; ();(a[i].maker, 20);cout << "Please enter the year made: "; cin >> a[i].year;}cout << "Here is your collection: " << endl; for (int i = 0; i < number;i++)cout << a[i].year << " " << a[i].maker <<endl; delete [] a;return 0;}n"; return 0;}n";return 0;}和的区别是:word != "done",因为当 word = done 一样时,返回值为1,不一样时才是返回0.;for(int k=0;k<=i;++k)cout<<"*"; cout<<endl;}return 0;}第六章分支语句和逻辑运算符n"; break;case 'p':cout<<"A maple is a pianist.\n"; break;case 't':cout<<"A maple is a tree.\n"; break;case 'g':cout<<"A maple is a game.\n";}return 0;}#include <iostream> usingnamespace std; void show();int main(){show();char choice;while (cin >> choice){switch(choice){case 'c' : cout << "It's a carnivore.\n"; break;case 'p' : cout << "It's a pianist.\n"; break;case 't' : cout << "A maple is a tree.\n"; break;case 'g' : cout << "It's a game.\n"; break;default : cout << "Please enter a c, p, t, or g:";}}return 0;}void show(){cout << "Please enter one of the following choices: \n" "c) carnivore p) pianist\n""t) tree g) game\n";}display by name b. display by title\n"<<"c. display by bopname d. diplay by preference\n"<<"q. quit\n";char ch;bop member[5]={{"Wimp Macho","English Teacher","DEMON",0},{"Raki Rhodes","Junior Programmer","BOOM",1},{"Celia Laiter","Super Star","MIPS",2},{"Hoppy Hipman","Analyst Trainee","WATEE",1},{"Pat Hand","Police","LOOPY",2}};cout<<"Enter your choice:";while(cin>>ch&&ch!='q'){switch(ch){case 'a':for(int i=0;i<5;i++)cout<<member[i].fullname<<endl; b reak; case 'b':for(int i=0;i<5;i++)cout<<member[i].title<<endl; b reak;case 'c':for(int i=0;i<5;i++)cout<<member[i].bopname<<endl; b reak; case 'd':for(int i=0;i<5;i++){if(member[i].preference==0)cout<<member[i].fullname<<endl; elseif(member[i].preference==1)cout<<member[i].title<<endl; e lseif(member[i].preference==2)cout<<member[i].bopname<<endl;}break;}cout<<"Next choice: ";}cout<<"Bye!\n";return 0;}#include <iostream> usingnamespace std; const int strsize =30; struct bop{char fullname[strsize]; chartitle[strsize]; charbopname[strsize]; int preference;};void show(); intmain(){bop A[5] ={{"Wimp Macho", "Teacher", "HAHA", 0},{"Raki Rhodes", "Junior Programmer", "LIAR", 1},{"Celia", "engineer", "MIPS", 2},{"Hoppy Hipman", "Analyst Trainee", "WAHU", 1},{"Pat Hand", "Student", "LOOPY", 2}};cout << "Benevolent Order of Programmers R eport\n"; show();cout << "Enter your choice: "; char choice;cin >> choice;while (choice != 'q'){switch(choice){case 'a' : cout << A[0].fullname << endl << A[1].fullname << e ndl<< A[2].fullname << endl << A[3].fullname << e ndl<< A[4].fullname << endl; break;case 'b' : cout << A[0].title << endl << A[1].title << e ndl<< A[2].title << endl << A[3].title << endl<< A[4].title << endl; break;case 'c' : cout << A[0].bopname << endl << A[1].bopname << e ndl<< A[2].bopname << endl << A[3].bopname << e ndl<< A[4].bopname << endl; break;case 'd' : cout << A[0].fullname << endl << A[1].title << e ndl<< A[2].bopname << endl << A[3].title << e ndl<< A[4].bopname << endl; break;default : cout << "That's not the proper c hoice.\n";}cout << "Next choice: "; cin >> choice;}cout << "Bye!\n"; return 0;}void show(){cout << "a. display by name b. display by title\n"<< "c. display by bopname d. display by preference\n"<< "q. quit\n";}ame); c out<<"请输入第"<<i+1<<"位捐款人捐款的数目:"; c in>>ps[i].money;();}cout<<"Grand Patrons:\n"; for(inti=0;i<num;++i) i f(ps[i].money>10000){cout<<ps[i].name<<"\n"<<ps[i].money<<endl;++temp;}if(temp==0)cout<<"none\n";cout<<"Patrons:\n"; f or(inti=0;i<num;++i)if(ps[i].money<=10000){cout<<ps[i].name<<"\n"<<ps[i].money<<endl;++temp;}if(temp==0)cout<<"none\n";delete [] ps; return0;}#include <iostream>#include <string> usingnamespace std; struct charity{string name; doublemoney;};int main(){int number; intcount = 0;cout << "Please enter the number of donator: "; cin >> number;charity *pt = new charity[number]; for (int i = 0; i <number; i++){cout << "Please enter your name: "; ();getline(cin, pt[i].name);cout << "Please enter the money you are going to donate: "; cin >> pt[i].money;if(pt[i].money > 10000) count++;}if(count == 0)cout << "None(money > 10000)"; else{cout << "Grand Patron\n"; for(int i = 0; i <number; i++){if(pt[i].money > 10000)cout << pt[i].name << " " << pt[i].money << endl;}}cout << endl;if(10 - count == 0)cout << "None(money < 10000)"; else{cout << "Patron\n";for(int i = 0; i < number; i++){if(pt[i].money < 10000)cout << pt[i].name << " " << pt[i].money << endl;}}return 0;}n"; exit(EXIT_FAILURE);}inFile>>ch; while()){++sum;inFile>>ch;}if())cout<<"End of file reached.\n"; else if())cout<<"Input terminated by data mismatch.\n"; elsecout<<"Input terminated for unkonwn reason.\n";cout<<"总共有"<<sum<<"个字符在这个文件中。

C primer plus(第五版)课后编程练习答案

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)的问题。

#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()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C++p r i m e r p l u s 编程练习答案注:本人暑假正在看这本书,顺便就把题目做了,均经过了编译器通过,无注释。

第二章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 *celsius+;}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=;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=;const double memter=;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/;float haoyou;haoyou=jialun;cout<<"转换成美国风格的耗油量(一加仑的里程,mpg):"<<haoyou<<"mpg."<<endl;}第四章待我上传。

相关文档
最新文档