C語(yǔ)言程序設(shè)計(jì)現(xiàn)代方法(第二版)習(xí)題答案_第1頁(yè)
C語(yǔ)言程序設(shè)計(jì)現(xiàn)代方法(第二版)習(xí)題答案_第2頁(yè)
C語(yǔ)言程序設(shè)計(jì)現(xiàn)代方法(第二版)習(xí)題答案_第3頁(yè)
C語(yǔ)言程序設(shè)計(jì)現(xiàn)代方法(第二版)習(xí)題答案_第4頁(yè)
C語(yǔ)言程序設(shè)計(jì)現(xiàn)代方法(第二版)習(xí)題答案_第5頁(yè)
已閱讀5頁(yè),還剩85頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

Chapter2

AnswerstoSelectedExercises

[was#2](a)Theprogramcontainsonedirective(#include)andfourstatements(threecallsofprintfandonereturn).

(b)

Parkinson'sLaw:

Workexpandssoastofillthetime

availableforitscompletion.

[was#4]

#include<>

intmain(void)

{

intheight=8,length=12,width=10,volume;

volume=height*length*width;

printf("Dimensions:%dx%dx%d\n",length,width,height);

printf("Volume(cubicinches):%d\n",volume);

printf("Dimensionalweight(pounds):%d\n",(volume+165)/166);

return0;

}

[was#6]Here'sonepossibleprogram:

#include<>intmain(void)

{

inti,j,k;

floatx,y,z;

printf("Valueofi:%d\n",i);

printf("Valueofj:%d\n",j);

printf("Valueofk:%d\n",k);

printf("Valueofx:%g\n",x);

printf("Valueofy:%g\n",y);

printf("Valueofz:%g\n",z);

return0;

}

WhencompiledusingGCCandthenexecuted,thisprogramproducedthe

followingoutput:

Val

ue

of

i:

5618848

Val

ue

of

j:

0

Val

ue

of

k:

6844404

Val

ue

of

x:

Val

ue

of

y:

Val

ue

of

z:

Thevaluesprinteddependonmanyfactors,sothechancethatyou'llgetexactlythesenumbersissmall.

intmain(void)

*,p,),/,3,

theprogram

[was#10](a)isnotlegalbecause100_bottlesbeginswithadigit.

[was#12]Thereare14tokens:a,=,(,3,*,q,-,p,and;.

AnswerstoSelectedProgrammingProjects

4.[was#8;modified]

#include<>

intmain(void)

{

floatoriginal_amount,amount_with_tax;

printf("Enteranamount:");

scanf("%f",&original_amount);

amount_with_tax=original_amount*1.05f;printf("Withtaxadded:$%.2f\n",amount_with_tax);

return0;

}

Theamount_with_taxvariableisunnecessary.Ifweremoveit,isslightlyshorter:

#include<>

floatoriginal_amount;

printf("Enteranamount:");

scanf("%f",&original_amount);

printf("Withtaxadded:$%.2f\n",original_amount*1.05f);

return0;

}

Chapter3

AnswerstoSelectedExercises

2.[was#2]

printf("%",x);

printf("%",x);

printf("%-8.3f",x);

printf("%6.0f",x);

respectively.

5.[was#8]Thevaluesofx,i,andywillbe,45,and.6

AnswerstoSelectedProgrammingProjects

[was#4;modified]

#include<>

intmain(void)

intmonth,day,year;

printf("Enteradate(mm/dd/yyyy):");

scanf("%d/%d/%d",&month,&day,&year);

printf("Youenteredthedate%d%.2d%.2d\n",year,month,day);

return0;

}

3.[was#6;modified]

#include<>

intmain(void)

{

intprefix,group,publisher,item,check_digit;

printf("EnterISBN:");

scanf("%d-%d-%d-%d-%d",&prefix,&group,&publisher,&item,&check_digit);

printf("GS1prefix:%d\n",prefix);

printf("Groupidentifier:%d\n",group);

printf("Publishercode:%d\n",publisher);

printf("Itemnumber:%d\n",item);

printf("Checkdigit:%d\n",check_digit);

/*Thefiveprintfcallscanbecombinedasfollows:

printf("GS1prefix:%d\nGroupidentifier:%d\nPublishercode:%d\nItemnumber:%d\nCheckdigit:%d\n",

prefix,group,publisher,item,check_digit);

2.[was#4]

*/

return0;

}

Chapter4

AnswerstoSelectedExercises

[was#2]NotinC89.Supposethatiis9andjis7.Thevalueof(-i)/jcouldbeeither-1or-2,dependingontheimplementation.Ontheotherhand,thevalueof-(i/j)isalways-1,regardlessoftheimplementation.

InC99,ontheotherhand,thevalueof(-i)/jmustbeequaltothevalueof-(i/j).

[was#6]

TOC\o"1-5"\h\z

638

321

2-13

000

13.[was#8]Theexpression++iisequivalentto(i+=1).Thevalueofbothexpressionsisiaftertheincrementhasbeenperformed.

AnswerstoSelectedProgrammingProjects

#include<>

10.[was#16]Theoutputis

intmain(void){

intn;

printf("Enterathree-digitnumber:");

scanf("%d",&n);

/100);

printf("Thereversalis:%d%d%d\n",n%10,(n/10)%10,n

return0;

}

Chapter5

AnswerstoSelectedExercises

2.

[was

#2]

(a)

1

(b)

1

(c)

1

(d)

1

4.

[was

#4](i>

j)-(i<j)

6.

[was

#12]Yes,

thestatementislegal.Whennisequalto5

not

hing,

since5

isnotequalto-9.

itdoes

onetwo

#include<>

4.[was#8;modified]

sincetherearenobreakstatementsafterthecases.

AnswerstoSelectedProgrammingProjects

2.[was#6]

#include<>

intmain(void)

{

inthours,minutes;

printf("Entera24-hourtime:");

scanf("%d:%d",&hours,&minutes);

printf("Equivalent12-hourtime:");

if(hours==0)

printf("12:%.2dAM\n",minutes);

elseif(hours<12)

printf("%d:%.2dAM\n",hours,minutes);

elseif(hours==12)

printf("%d:%.2dPM\n",hours,minutes);

else

printf("%d:%.2dPM\n",hours-12,minutes);

return0;

}

#include<>intmain(void)

{

intspeed;

printf("Enterawindspeedinknots:");scanf("%d",&speed);

if(speed<1)printf("Calm\n");

elseif(speed<=3)printf("Lightair\n");

elseif(speed<=27)printf("Breeze\n");

elseif(speed<=47)printf("Gale\n");

elseif(speed<=63)printf("Storm\n");

elseprintf("Hurricane\n");

return0;

}

6.[was#10]

10.[was#14]

#include<>

intmain(void){

intcheck_digit,d,i1,i2,i3,i4,i5,j1,j2,j3,j4,j5,first_sum,second_sum,total;

printf("Enterthefirst(single)digit:");

scanf("%1d",&d);

printf("Enterfirstgroupoffivedigits:");scanf("%1d%1d%1d%1d%1d",&i1,&i2,&i3,&i4,&i5);

printf("Entersecondgroupoffivedigits:");scanf("%1d%1d%1d%1d%1d",&j1,&j2,&j3,&j4,&j5);

printf("Enterthelast(single)digit:");

scanf("%1d",&check_digit);

first_sum=d+i2+i4+j1+j3+j5;

second_sum=i1+i3+i5+j2+j4;

total=3*first_sum+second_sum;

if(check_digit==9-((total-1)%10))printf("VALID\n");

else

printf("NOTVALID\n");

return0;

}

intmain(void){

intgrade;

printf("Enternumericalgrade:");scanf("%d",&grade);

if(grade<0||grade>100){printf("Illegalgrade\n");return0;

}

switch(grade/10){

case10:

case9:

printf("Lettergrade:A\n");

break;

case8:

printf("Lettergrade:B\n");

break;

case7:

printf("Lettergrade:C\n");

break;

case6:

printf("Lettergrade:D\n");

break;

case5:

case4:

case3:

case2:

case1:

case0:printf("Lettergrade:F\n");

break;

}

return0;

}

Chapter6

AnswerstoSelectedExercises

4.[was#10](c)isnotequivalentto(a)and(b),becauseibeforetheloopbodyisexecuted.

10.[was#12]Considerthefollowingwhileloop:

while(…){

■■■

continue;

■■■

}

Theequivalentcodeusinggotowouldhavethefollowing

while(…){

■■■

gotoloop_end;

isincremented

appearance:

loop_end:;/*nullstatement*/

12.[was#14]

for(d=2;d*d<=n;d++)

if(n%d==0)

break;

Theifstatementthatfollowstheloopwillneedtobemodifiedaswell:if(d*d<=n)

printf("%disdivisibleby%d\n",n,d);

else

printf("%disprime\n",n);

14.[was#16]Theproblemisthesemicolonattheendofthefirstline.

Ifweremoveit,thestatementisnowcorrect:

if(n%2==0)

printf("niseven\n");

AnswerstoSelectedProgrammingProjects

[was#2]

#include<>

intmain(void)

intm,n,remainder;

printf("Entertwointegers:");

scanf("%d%d",&m,&n);

while(n!=0){

remainder=m%n;

m=n;

n=remainder;

}

printf("Greatestcommondivisor:%d\n",m);

return0;

}

4.[was#4]

#include<>

intmain(void)

{

floatcommission,value;

printf("Entervalueoftrade:");

scanf("%f",&value);

while(value!=0.0f){

if(value<2500.00f)

commission=30.00f+.017f*value;

elseif(value<6250.00f)

commission=56.00f+.0066f*value;

elseif(value<20000.00f)

commission=76.00f+.0034f*value;

elseif(value<50000.00f)

commission=100.00f+.0022f*value;

elseif(value<500000.00f)

commission=155.00f+.0011f*value;else

commission=255.00f+.0009f*value;

if(commission<39.00f)

commission=39.00f;

printf("Commission:$%.2f\n\n",commission);

printf("Entervalueoftrade:");

scanf("%f",&value);

}

return0;

}

6.[was#6]

#include<>

intmain(void)

{

inti,n;

printf("Enterlimitonmaximumsquare:");

scanf("%d",&n);

for(i=2;i*i<=n;i+=2)

printf("%d\n",i*i);

return0;

}

8.[was#8]

#include<>

intmain(void)

{

inti,n,start_day;

printf("Enternumberofdaysinmonth:");

scanf("%d",&n);

printf("Enterstartingdayoftheweek(1=Sun,7=Sat):");

scanf("%d",&start_day);

/*printanyleading"blankdates"*/

for(i=1;i<start_day;i++)

printf("");

/*nowprintthecalendar*/

for(i=1;i<=n;i++){

printf("%3d",i);

if((start_day+i-1)%7==0)

printf("\n");

return0;

}

Chapter7

AnswerstoSelectedExercises

[was#4](b)isnotlegal.

[was#6](d)isillegal,sinceprintfrequiresastring,notacharacter,asitsfirstargument.

10.[was#14]unsignedint,becausethe(int)castappliesonlytoj,notj*k.

12.[was#16]Thevalueofiisconvertedtofloatandaddedtof,thentheresultisconvertedtodoubleandstoredind.

14.[was#18]No.Convertingftointwillfailifthevaluestoredinfexceedsthelargestvalueoftypeint.

AnswerstoSelectedProgrammingProjects

1.[was#2]shortintvaluesareusuallystoredin16bits,andlongintvaluesareusuallystoredin32bits,withfailureoccurringat46341.

2.[was#8]

#include<>intmain(void)

{

inti,n;

charch;

printf("Thisprogramprintsatableofsquares.\n");

printf("Enternumberofentriesintable:");

scanf("%d",&n);

ch=getchar();

/*disposeofnew-linecharacterfollowingnumberofentries*/

/*couldsimplybegetchar();*/

for(i=1;i<=n;i++){printf("%10d%10d\n",i,i*i);

if(i%24==0){

printf("PressEntertocontinue...");

ch=getchar();/*orsimplygetchar();*/

}

}

return0;

}

[was#10]

#include<>

#include<>

intmain(void)

{

intsum=0;

charch;

printf("Enteraword:");

while((ch=getchar())!='\n')

switch(toupper(ch)){

case'D':case'G':

sum+=2;break;

case'B':case'C':case'M':case'P':

sum+=3;break;

'Y':

case'F':case'H':case'V':case'W':case

sum+=4;break;

case'K':

sum+=5;break;

case'J':case'X':

sum+=8;break;

case'Q':case'Z':

sum+=10;break;

default:

sum++;break;

}

printf("Scrabblevalue:%d\n",sum);

return0;

[was#12]

#include<>

intmain(void)

{

printf("Sizeofint:%d\n",(int)sizeof(int));

printf("Sizeofshort:%d\n",(int)sizeof(short));

printf("Sizeoflong:%d\n",(int)sizeof(long));

printf("Sizeoffloat:%d\n",(int)sizeof(float));

printf("Sizeofdouble:%d\n",(int)sizeof(double));

printf("Sizeoflongdouble:%d\n",(int)sizeof(longdouble));

return0;

}

Sincethetypeofasizeofexpressionmayvaryfromoneimplementationtoanother,it'snecessaryinC89tocastsizeofexpressionstoaknowntypebeforeprintingthem.Thesizesofthebasictypesaresmallnumbers,soit'ssafetocastthemtoint.(Ingeneral,however,it'sbesttocastsizeofexpressionstounsignedlongandprintthemusing%lu.)InC99,wecanavoidthecastbyusingthe%zuconversionspecification.

Chapter8

AnswerstoSelectedExercises

1.[was#4]Theproblemwithsizeof(a)/sizeof(t)isthatitcan'teasilybecheckedforcorrectnessbysomeonereadingtheprogram.(Thereaderwouldhavetolocatethedeclarationofaandmakesurethatitselementshavetypet.)

2.[was#8]Touseadigitd(incharacterform)asasubscriptintothearraya,wewouldwritea[d-'0'].Thisassumesthatdigitshaveconsecutivecodesintheunderlyingcharacterset,whichistrueofASCIIandotherpopularcharactersets.

[was#10]

constintsegments[10][7]={{1,

1,1,

1,1,

1}

{0,

1,1}

{1,

1,0,

1,1,

0,

1},

{1,

1,1,

1,0,

0,

1},

{0,

1,1,

0,0,

1,

1},

{1,

0,1,

1,0,

1,

1},

{1,

0,1,

1,1,

1,

1},

{1,

1,1}

{1,

1,1,

1,1,

1,

1},

{1,

1,1,

1,0,

1,

1}}

AnswerstoSelectedProgrammingProjects2.[was#2]

#include<>intmain(void)

{

intdigit_count[10]={0};

intdigit;

longn;

printf("Enteranumber:");

scanf("%ld",&n);

while(n>0){

digit=n%10;

digit_count[digit]++;

n/=10;

}

printf("Digit:");

for(digit=0;digit<=9;digit++)

printf("%3d",digit);

printf("\nOccurrences:");

for(digit=0;digit<=9;digit++)

printf("%3d",digit_count[digit]);

printf("\n");

return0;

}

5.[was#6]#include<>

#defineNUM_RATES((int)(sizeof(value)/sizeof(value[0])))

#defineINITIAL_BALANCE

intmain(void)

{

inti,low_rate,month,num_years,year;

doublevalue[5];

printf("Enterinterestrate:");

scanf("%d",&low_rate);

printf("Enternumberofyears:");

scanf("%d",&num_years);

printf("\nYears");

for(i=0;i<NUM_RATES;i++){

printf("%6d%%",low_rate+i);

value[i]=INITIAL_BALANCE;

}

printf("\n");

for(year=1;year<=num_years;year++){

printf("%3d",year);

for(i=0;i<NUM_RATES;i++){

for(month=1;month<=12;month++)

value[i]+=((double)(low_rate+i)/12)/*value[i];

printf("%7.2f",value[i]);

}

printf("\n");

return0;

}

[was#12]

#include<>

#defineNUM_QUIZZES5

#defineNUM_STUDENTS5

intmain(void)

{

intgrades[NUM_STUDENTS][NUM_QUIZZES];

inthigh,low,quiz,student,total;

for(student=0;student<NUM_STUDENTS;student++){

printf("Entergradesforstudent%d:",student+1);

for(quiz=0;quiz<NUM_QUIZZES;quiz++)

scanf("%d",&grades[student][quiz]);

}

printf("\nStudentTotalAverage\n");

for(student=0;student<NUM_STUDENTS;student++){

printf("%4d",student+1);

total=0;

for(quiz=0;quiz<NUM_QUIZZES;quiz++)

total+=grades[student][quiz];

printf("%3d%3d\n",total,total/NUM_QUIZZES);

}

printf("\nQuizAverageHighLow\n");

for(quiz=0;quiz<NUM_QUIZZES;quiz++){

printf("%3d",quiz+1);

total=0;

high=0;

low=100;

for(student=0;student<NUM_STUDENTS;student++){total+=grades[student][quiz];

if(grades[student][quiz]>high)

high=grades[student][quiz];

if(grades[student][quiz]<low)

low=grades[student][quiz];

}

low);

printf("%3d%3d%3d\n",total/NUM_STUDENTS,high

}

return0;

}

Chapter9

AnswerstoSelectedExercises2.[was#2]intcheck(intx,inty,intn)

{

return(x>=0&&x<=n-1&&y>=0&&y<=n-1);

}

4.[was#4]

intday_of_year(intmonth,intday,intyear)

{

intnum_days[]={31,28,31,30,31,30,31,31,30,31,30,31};intday_count=0,i;

for(i=1;i<month;i++)

day_count+=num_days[i-1];

/*adjustforleapyears,assumingtheyaredivisibleby4*/

if(year%4==0&&month>2)day_count++;

returnday_count+day;

}

Usingtheexpressionyear%4==0totestforleapyearsisnotcompletelycorrect.Centuriesarespecialcases:ifayearisamultipleof100,thenitmustalsobeamultipleof400inordertobealeapyear.Thecorrecttestis

year%4==0&&(year%100!=0||year%400==0)6.[was#6;modified]intdigit(intn,intk)

{

inti;

for(i=1;i<k;i++)

n/=10;

returnn%10;

}

8.[was#8](a)and(b)arevalidprototypes.(c)isillegal,sinceitdoesn'tspecifythetypeoftheparameter.(d)incorrectlyspecifiesthatfreturnsanintvalueinC89;inC99,omittingthereturntypeisillegal.

10.[was#10]

(a)

intlargest(inta[],intn)

{

inti,max=a[0];

for(i=1;i<n;i++)

if(a[i]>max)

max=a[i];

returnmax;

}

(b)

intaverage(inta[],intn)

{

inti,avg=0;

for(i=0;i<n;i++)

avg+=a[i];

returnavg/n;

}

(c)

intnum_positive(inta[],intn)

{

inti,count=0;

for(i=0;i<n;i++)

if(a[i]>0)

count++;

returncount;

}

15.[was#12;modified]

doublez)

doublemedian(doublex,doubley,

{

doubleresult;

if(x<=y)

if(y<=z)result=y;

elseif(x<=z)result=z;

elseresult=x;

else{

if(z<=y)result=y;

elseif(x<=z)result=x;

elseresult=z;

}

returnresult;

}

17.[was#14]

intfact(intn)

{

inti,result=1;

for(i=2;i<=n;i++)

result*=i;

returnresult;

}

19.[was#16]Thefollowingprogramteststhepbfunction:

#include<>

voidpb(intn);

intmain(void){

intn;

printf("Enteranumber:");

scanf("%d",&n);

printf("Outputofpb:");

pb(n);

printf("\n");

return0;

}

voidpb(intn)

{

if(n!=0){

pb(n/2);

putchar('0'+n%2);

}

}

pbprintsthebinaryrepresentationoftheargumentn,assumingthatnisgreaterthan0.(Wealsoassumethatdigitshaveconsecutivecodesintheunderlyingcharacterset.)Forexample:

Enteranumber:53

Outputofpb:110101

Atraceofpb'sexecutionwouldlooklikethis:

pb(53)findsthat53isnotequalto0,soitcalls

pb(26),whichfindsthat26isnotequalto0,soitcalls

pb(13),whichfindsthat13isnotequalto0,soitcalls

pb(6),whichfindsthat6isnotequalto0,soitcalls

pb(3),whichfindsthat3isnotequalto0,soit

calls

pb(1),whichfindsthat1isnotequalto0,so

itcalls

pb(0),whichfindsthat0isequalto0,so

itreturns,causing

pb(1)toprint1andreturn,causing

pb(3)toprint1andreturn,causing

pb(6)toprint0andreturn,causing

pb(13)toprint1andreturn,causing

pb(26)toprint0andreturn,causing

pb(53)toprint1andreturn.

Chapter10

AnswerstoSelectedExercises

1.[was#2](a)a,b,andcarevisible.

(b)a,anddarevisible.

(c)a,d,andearevisible.

aandfarevisible.

AnswerstoSelectedProgrammingProjects

3.[was#4]

#include<>/*C99only*/

#include<>

#include<>

#defineNUM_CARDS5

#defineRANK0

#defineSUIT1

/*externalvariables*/

inthand[NUM_CARDS][2];

/*01

0||

||

||

||

||

ranksuit

*/boolstraight,flush,four,three;

intpairs;/*canbe0,1,or2*/

/*prototypes*/

voidread_cards(void);

voidanalyze_hand(void);

voidprint_result(void);

/

/

*main:Callsread_cards,analyze_hand,andprint_result*

*repeatedly.*

//

intmain(void)

{

for(;;){

read_cards();

analyze_hand();

print_result();

}

}

/

/

*read_cards:Readsthecardsintotheexternalvariable*

*hand;checksforbadcardsandduplicate*

*cards.*

voidread_cards(void)

{

charch,rank_ch,suit_ch;

inti,rank,suit;

boolbad_card,duplicate_card;

intcards_read=0;

while(cards_read<NUM_CARDS){bad_card=false;

printf("Enteracard:");

rank_ch=getchar();switch(rank_ch){

case'0':

case'2':

case'3':

case'4':

case'5':

case'6':

case'7':

case'8':

case'9':

case't':case'T'

I?IIII

case'j':case'J'

case'q':case'Q'

case'k':case'K'

case'a':case'A'exit(EXIT_SUCCESS)rank=0;break;rank=1;break;rank=2;break;rank=3;break;rank=4;break;rank=5;break;rank=6;break;rank=7;break;rank=8;break;rank=9;break;rank=10;break;rank=11;break;rank=12;break;

default:bad_card=true;

}

suit_ch=getchar();

switch

(suit_ch)

{

case

'c':

case

'C':

suit=0;

break;

case

'd':

case

'D':

suit=1;

break;

case

'h':

case

'H':

suit=2;

break;

case

's':

case

'S':

suit=3;

break;

default:

bad_card

=true;

}

while((ch=getchar())!='\n')

if(ch!='')bad_card=true;if(bad_card){

printf("Badcard;ignored.\n");

continue;

}

duplicate_card=false;

for(i=0;i<cards_read;if(hand[i][RANK]==rankprintf("Duplicatecard;duplicate_card=true;break;

}

i++)

&&hand[i][SUIT]==suit){

ignored.\n");

if(!duplicate_card){

hand[cards_read][RANK]=rank;

hand[cards_read][SUIT]=suit;

cards_read++;

}

}

}

/

/

TOC\o"1-5"\h\z

*analyze_hand:Determineswhetherthehandcontainsa*

*straight,aflush,four-of-a-kind,*

*and/orthree-of-a-kind;determinesthe*

*numberofpairs;storestheresultsinto*

*theexternalvariablesstraight,flush,*

*four,three,andpairs.*

//

voidanalyze_hand(void)

{

intrank,suit,card,pass,run;

straight=true;

flush=true;

four=false;

three=false;

pairs=0;

/*sortcardsbyrank*/

for(pass=1;pass<NUM_CARDS;pass++)

for(card=0;card<NUM_CARDS-pass;card++){

rank=hand[card][RANK];

suit=hand[card][SUIT];

if(hand[card+1][RANK]<rank){hand[card][RANK]=hand[card+1][RANK];hand[card][SUIT]=hand[card+1][SUIT];hand[card+1][RANK]=rank;hand[card+1][SUIT]=suit;

}

}

/*checkforflush*/

suit=hand[0][SUIT];

for(card=1;card<NUM_CARDS;card++)

if(hand[card][SUIT]!=suit)flush=false;

/*checkforstraight*/

for(card=0;card<NUM_CARDS-1;card++)

if(hand[card][RANK]+1!=hand[card+1][RANK])straight=false;

/*checkfor4-of-a-kind,3-of-a-kind,andpairsbylookingfor"runs"ofcardswithidenticalranks*/card=0;

while(card<NUM_CARDS){

rank=hand[card][RANK];

run=0;

do{

run++;

card++;

}while(card<NUM_CARDS&&hand[card][RANK]==rank);

switch

(run){

case

2:

pairs++;

break;

case

3:

three=true;

break;

case

4:

four=true;

break;

}

}

}

/

/

TOC\o"1-5"\h\z

*print_result:Printstheclassificationofthehand,*

*basedonthevaluesoftheexternal*

*variablesstraight,flush,four,three,*

*andpairs.*

//

voidprint_result(void)

{

if(straight&&flush)printf("Straightflush");

elseif

(four)

printf("Fourofakind");

elseif

(three&&

pairs==1)

printf("Fullhouse");

elseif

(flush)

printf("Flush");

elseif

(straight)

printf("Straight");

elseif

(three)

printf("Threeofakind")

elseif

(pairs==2)

printf("Twopairs");

elseif(pairs==1)printf("Pair");

elseprintf("Highcard");printf("\n\n");

}

5.[was#6]

#include<>/*C99only*/

#include<>

#include<>

#defineNUM_RANKS13

#defineNUM_SUITS4

#defineNUM_CARDS5

/*externalvariables*/

intnum_in_rank[NUM_RANKS];

intnum_in_suit[NUM_SUITS];

boolstraight,flush,four,three;

intpairs;/*canbe0,1,or2*/

/*prototypes*/

voidread_cards(void);

voidanalyze_hand(void);

voidprint_result(void);

/

/

*main:Callsread_cards,analyze_hand,andprint_result*

repeatedly.

//

intmain(void)

{

for(;;){

read_cards();

analyze_hand();

print_result();

}

}

*read_cards:Readsthecardsintotheexternal*

*variablesnum_in_rankandnum_in_suit;*

*checksforbadcardsandduplicatecards.*

//

voidread_cards(void)

{

boolcard_exists[NUM_RANKS][NUM_SUITS];

charch,rank_ch,suit_ch;

intrank,suit;

boolbad_card;

intcards_read=0;

for(rank=0;rank<NUM_RANKS;rank++){

num_in_rank[rank]=0;

for(suit=0;suit<NUM_SUITS;suit++)

card_exists[rank][suit]=false;

}

for(suit=0;suit<NUM_SUITS;suit++)

num_in_suit[suit]=0;

while(cards_read<NUM_CARDS){

bad_card=false

J

printf("Entera

card:

");

rank_ch

=getchar();

switch

(rank_ch)

{

case

'0':

exit(EXIT_SUCCESS)

case

'2':

rank=

0;break;

case

'3':

rank=

1;break;

case

'4':

rank=

2;break;

case

'5':

rank=

3;break;

case

'6':

rank=

4;break;

case

'7':

rank=

5;break;

case

'8':

rank=

6;break;

case

'9':

rank=

7;break;

case

't':case

'T':

rank=

8;break;

case

'j':case

'J':

rank=

9;break;

case

'q':case

'Q':

rank=

10;break;

case

'k':case

'K':

rank=

11;break;

case

'a':case

'A':

rank=

12;break;

default:

bad_card=true;

suit_ch=getchar();

switch

(suit_ch)

{

case

'c':

case

'C':

suit=0;

break;

case

'd':

case

'D':

suit=1;

break;

case

'h':

case

'H':

suit=2;

break;

case

's':

case

'S':

suit=3;

break;

default:bad_card=true;

}

while((ch=getchar())!='\n')

if(ch!='')bad_card=true;

if(bad_card)

printf("Badcard;ignored.\n");

elseif(card_exists[rank][suit])

printf("Duplicatecard;ignored.\n");else{

num_in_rank[rank]++;

num_in_suit[suit]++;

card_exists[rank][suit]=true;cards_read++;

}

}

}

TOC\o"1-5"\h\z

*analyze_hand:Determineswhetherthehandcontainsa*

*straight,aflush,four-of-a-kind,*

*and/orthree-of-a-kind;determinesthe*

*numberofpairs;storestheresultsinto*

*theexternalvariablesstraight,flush,*

*four,three,andpairs.*

//

voidanalyze_hand(void)

{

intnum_consec=0;

intrank,suit;

straight=false;

flush=false;

four=false;

three=false;

pairs=0;

/*checkforflush*/

for(suit=0;suit<NUM_SUITS;suit++)

if(num_in_suit[suit]==NUM_CARDS)

flush=true;

/*checkforstraight*/

rank=0;

while(num_in_rank[rank]==0)rank++;

for(;rank<NUM_RANKS&&num_in_rank[rank]>0;rank++)

num_consec++;

if(num_consec==NUM_CARDS){

straight=true;

return;

}

/*checkforace-lowstraight*/

if(num_consec==NUM_CARDS-1&&

num_in_rank[0]>0&&num_in_rank[NUM_RANKS-1]>0){straight=true;

return;

}

/*checkfor4-of-a-kind,3-of-a-kind,andpairs*/

for(rank=0;rank<NUM_RANKS;rank++){

if(num_in_rank[rank]==4)four=true;

if(num_in_rank[rank]==3)three=true;

if(num_in_rank[rank]==2)pairs++;

}

}

/

/

TOC\o"1-5"\h\z

*print_result:Printstheclassificationofthehand,*

*basedonthevaluesoftheexternal*

*variablesstraight,flush,four,three,*

*andpairs.*

//

voidprint_result(void)

{

4.[was#4;modified]

if(straight&&flush)elseif(four)elseif(three&&

pairs==1)

elseif(flush)

elseif(straight)

elseif(three)

elseif(pairs==2)

elseif(pairs==1)else

printf("Straightflush");printf("Fourofakind");

printf("Fullhouse");printf("Flush");printf("Straight");

printf("Threeofakind");printf("Twopairs");

printf("Pair");printf("Highcard");

printf("\n\n");

}

Chapter11

AnswerstoSelectedExercises

2.[was#2](e),(f),and(i)arelegal.(a)isillegalbecausepisapointertoanintegerandiisaninteger.(b)isillegalbecause*pisanintegerand&iisapointertoaninteger.(c)isillegalbecause&pisapointertoapointertoanintegerandqisapointertoaninteger.(d)isillegalforreasonssimilarto(c).(g)isillegalbecausepisapointertoanintegerand*qisaninteger.(h)isillegalbecause*pisanintegerandqisapointertoaninteger.

voidswap(int*p,int*q)

{

inttemp;

temp=*p;

*p=*q;

*q=temp;

}

6.[was#6]

voidfind_two_largest(inta[],intn,int*largest,

int*second_largest)

{

inti;

if(a[0]>a[1]){

*largest=a[0];

*second_largest=a[1];

}else{

*largest=a[1];

*second_largest=a[0];

}

for(i=2;i<n;i++)

if(a[i]>*largest){

*second_largest=*largest;

*largest=a[i];

}elseif(a[i]>*second_largest)

*second_largest=a[i];

Chapter12

AnswerstoSelectedExercises

2.[was#2]Thestatementisillegalbecausepointerscannotbeadded.

Here'salegalstatementthathasthedesiredeffect:

middle=low+(high-low)/2;

Thevalueof(high-low)/2isaninteger,notapointer,soitcanlegallybeaddedtolow.

4.[was#6]

int*top_ptr;

voidmake_empty(void)

{

top_ptr=&contents[0];

}

boolis_empty(void)

{

returntop_ptr==&contents[0];

}

boolis_full(void)

returntop_ptr==&contents[STACK_SIZE];

}

6.[was#10;modified]

intsum_array(constinta[],intn)

{

int*p,sum;

sum=0;

for(p=a;p<a+n;p++)

sum+=*p;

returnsum;

}

13.[was#12;modified]

#defineN10

doubleident[N][N],*p;

intnum_zeros=N;

for(p=&ident[0][0];p<=&ident[N-1][N-1];p++)

if(num_zeros==N){

*p=;

num_zeros=0;

}else{

*p=;

num_zeros++;

15.[was#14]

int*p;

for(p=temperatures[i];p<temperatures[i]+24;p++)

printf("%d",*p);

AnswerstoSelectedProgrammingProjects

1.[was#4]

(a)

#include<>

#defineMSG_LEN80/*maximumlengthofmessage*/intmain(void)

{

charmsg[MSG_LEN];

inti;

printf("Enteramessage:

");

for(i=0;i<MSG_LEN;

i++){

msg[i]=getchar();if(msg[i]=='\n')

break;

printf("Reversalis:");

for(i--;i>=0;i--)

putchar(msg[i]);

putchar('\n');

return0;

}

(b)

#include<>

#defineMSG_LEN80/*maximumlengthofmessage*/intmain(void)

{

charmsg[MSG_LEN],*p;

printf("Enteramessage:");

for(p=&msg[0];p<&msg[MSG_LEN];p++){

*p=getchar();

if(*p=='\n')

break;

}

printf("Reversalis:");

for(p--;p>=&msg[0];p--)

putchar(*p);

putchar('\n');

return0;

3.[was#8]

#include<>

#defineMSG_LEN80/*maximumlengthofmessage*/intmain(void)

{

charmsg[MSG_LEN],*p;

printf("Enteramessage:");

for(p=msg;p<msg+MSG_LEN;p++){

*p=getchar();

if(*p=='\n')

break;

}

printf("Reversalis:");

for(p--;p>=msg;p--)

putchar(*p);

putchar('\n');

return0;

}

Chapter13

AnswerstoSelectedExercises2.[was#2]

(a)

Illegal

;pisnotacharacter

(b)

Legal;

output

isa.

(c)

Legal;

output

isabc.

(d)

Illegal

;*pis

nota

pointer.

4.

[was#4]

(a)

int

read_line(char

str[],

intn)

{

intch,i

=0;

while((ch=getchar())!='\n')

if(i==0&&isspace(ch))

;/*ignore*/

elseif(i<n)

str[i++]=ch;

str[i]='\0';

returni;

}

(b)

intread_line(charstr[],intn)

intch,i=0;

while(!isspace(ch=getchar()))if(i<n)

str[i++]=ch;

str[i]='\0';

returni;

}

(c)

intread_line(charstr[],intn)

{

intch,i=0;

do{

ch=getchar();

if(i<n)

str[i++]=ch;

}while(ch!='\n');

str[i]='\0';

returni;

}

intread_line(charstr[],intn)

{

8.[was#10]tired-or-wired

intch,i;

for(i=0;i<n;i++){

ch=getchar();

if(ch=='\n')

break;

str[i]=ch;

}

str[i]='\0';

returni;

}

6.[was#6]

voidcensor(chars[])

{

inti;

for(i=0;s[i]!='\0';i++)

if(s[i]=='f'&&s[i+1]=='o'&&s[i+2]=='o')

s[i]=s[i+1]=s[i+2]='x';

}

Notethattheshort-circuitevaluationof&&preventstheifstatement

fromtestingcharactersthatfollowthenullcharacter.

#

.[was#14]

#include<>

10.[was#12]Thevalueofqisundefined,sothecallofstrcpyattemptstocopythestringpointedtobypintosomeunknownareaofmemory.Exercise2inChapter17discusseshowtowritethisfunctioncorrectly.

15.[was#8]

(a)3

(b)0

(c)Thelengthofthelongestprefixofthestringsthatconsistsentirelyofcharactersfromthestringt.Or,equivalently,thepositionofthefirstcharacterinsthatisnotalsoint.

16.[was#16]

intcount_spaces(constchar*s)

{

intcount=0;

while(*s)

if(*s++=='')

count++;

returncount;

}

AnswerstoSelectedProgrammingProjects

#include<>#defineWORD_LEN20

voidread_line(charstr[],intn);

intmain(void)

{

charsmallest_word[WORD_LEN+1],

largest_word[WORD_LEN+1],

current_word[WORD_LEN+1];printf("Enterword:");

read_line(current_word,WORD_LEN);

strcpy(smallest_word,strcpy(largest_word,current_word));while(strlen(current_word)!=4){

printf("Enterword:");

read_line(current_word,WORD_LEN);

if(strcmp(current_word,smallest_word)<0)strcpy(smallest_word,current_word);

if(strcmp(current_word,largest_word)>0)

strcpy(largest_word,current_word);

}

printf("\nSmallestword:%s\n",smallest_word);

printf("Largestword:%s\n",largest_word);

return0;

#

.[was#20]

#include<>

voidread_line(charstr[],intn){

intch,i=0;

while((ch=getchar())!='\n')if(i<n)

str[i++]=ch;

str[i]='\0';

}

[was#18]

#include<>

intmain(intargc,char*argv[]){

inti;

for(i=argc-1;i>0;i--)printf("%s",argv[i]);

printf("\n");

return0;

}

#include<>

#include<>

#defineNUM_PLANETS9

intstring_equal(constchar*s,constchar*t);intmain(intargc,char*argv[])

{

char*planets[]={"Mercury","Venus","Earth",

II■IIIIII■丄IIHC丄II

"Mars","Jupiter","Saturn",

"Uranus","Neptune","Pluto"}

inti,

j;

for(i

=1;

i<argc;i++){

for

(j=0

;j<NUM_PLANETS;j++)

if(string_equal(argv[i],planets[j])){printf("%sisplanet%d\n",argv[i],j+1);break;

}

if(j==NUM_PLANETS)

printf("%sisnotaplanet\n",argv[i]);

}

return0;

}intstring_equal(constchar*s,constchar*t)

{

inti;

for(i=0;toupper(s[i])==toupper(t[i]);i++)

if(s[i]=='\0')

return1;

return0;

}

Chapter14

AnswerstoSelectedExercises

2.[was#2]#defineNELEMS(a)((int)(sizeof(a)/sizeof(a[0])))

4.[was#4]

Oneproblemstemsfromthelackofparenthesesaroundthereplacementlist.Forexamp

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論