C語言編程練習(xí)_第1頁
C語言編程練習(xí)_第2頁
C語言編程練習(xí)_第3頁
C語言編程練習(xí)_第4頁
C語言編程練習(xí)_第5頁
已閱讀5頁,還剩99頁未讀, 繼續(xù)免費閱讀

下載本文檔

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

文檔簡介

會計學(xué)1C語言編程練習(xí)1/17/2023Chapter4ManagingInputandOutputOperations 4.2main() { floatx,y; printf("Pleaseinputthevalueofxandy:\n"); printf("x="); scanf("%f",&x); printf("y="); scanf("%f",&y); printf("(a)(x+y)/(x-y)=%f\n",(x+y)/(x-y)); printf("(b)(x+y)/2=%f\n",(x+y)/2); printf("(c)(x+y)(x-y)=%f\n",(x+y)*(x-y));}第1頁/共104頁1/17/2023Chapter4ManagingInputandOutputOperations 4.34.3Writeaprogramtoreadthefollowingnumbers,roundthemofftothenearestintegersandprintouttheresultsinintegerform:

35.7 50.21 -23.73 -46.45第2頁/共104頁1/17/2023Chapter4ManagingInputandOutputOperations 4.3main() { floatx; printf("Pleaseinputthenumber:"); scanf("%f",&x); printf("Thenumberis:%.0f\n",x);}第3頁/共104頁1/17/2023Chapter4ManagingInputandOutputOperations 4.54.5Writeaninteractiveprogramtodemonstratetheprocessofmultiplication.Theprogramshouldasktheusertoentertwotwo-digitintegersandprinttheproductofintegersasshownbelow. 45

× 37 7×45is 315 3×45is 135 Addthem 1665 第4頁/共104頁1/17/2023Chapter4ManagingInputandOutputOperations 4.5main() { intx,y,m,n; printf("Pleaseinput2two-digitintegers:"); scanf("%d%d",&x,&y); printf("\n\t\t%6d\n\t\t*%5d\n",x,y); printf("\t\t______\n"); printf("%d*%dis\t\t%6d\n",y%10,x,y%10*x); printf("%d*%dis\t\t%5d\n",y/10,x,y/10*x); printf("\t\t______\n"); printf("Addthem\t%6d\n",y*x); printf("\t\t______\n");}第5頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.15.1Writeaprogramtodeterminewhetheragivennumberis'odd'of'even'andprintthemessage

NUMBERISEVEN

or NUMBERISODD (a)withoutusingelseoption,and (b)withelseoption.第6頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.1main() /*(a)*/{ intn; printf("Pleaseinputaninteger:"); scanf("%d",&n);

if(n%2) printf("%dISODD\n",n); if(n%2==0) printf("%dISEVEN\n",n);

}第7頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.1main() /*(b)*/{ intn; printf("Pleaseinputaninteger:"); scanf("%d",&n);

if(n%2) printf("%dISODD\n",n); else printf("%dISEVEN\n",n);

}第8頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.35.3Asetoftwolinerequationswithtwounknownx1andx2isgivenbelow: ax1+bx2=m cx1+dx2=n Thesethasauniquesolution

providedthedenominatorad-cbisnotequaltozero. Writeaprogramthatwillreadthevaluesofconstantsa,b,c,d,mandnandcomputethevaluesofx1andx2.Anappropriatemessageshouldbeprintedifad-cb=0.第9頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.3main() { floata,b,c,d,m,n; printf("Aboutasetoftwolinerequations:\n"); printf("\tax1+bx2=m\n\tcx1+dx2=n\n"); printf("Pleaseinputthevalueofa,b,c,d,mandn:\n"); printf("a="); scanf("%f",&a); printf("b="); scanf("%f",&b); printf("c="); scanf("%f",&c); printf("d="); scanf("%f",&d); printf("m="); scanf("%f",&m); printf("n="); scanf("%f",&n);

printf("\nAboutthesetoftwolinerequations:\n"); printf("\t%.2fx1+%.2fx2=%.2f\n\t%.2fx1+%.2fx2=%.2f\n",a,b,m,c,d,n); if(a*d-c*b==0) printf("Error:thedenominatoriszero!\n"); else printf("Theresult:x1=%.2f,x2=%.2f\n",

(m*d-b*n)/(a*d-c*b),(n*a-m*c)/(a*d-c*b));

}第10頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.55.5Admissiontoaprofessionalcourseissubjecttothefollowingconditions: (a)MarksinMathematics>=60 (b)MarksinPhysics>=50 (c)MarksinChemistry>=40 (d)Totalinallthreesubjects>=200 or TotalinMathematicsandPhysics>=150 Giventhemarksinthethreesubjects,writeaprogramtoprocesstheapplicationstolisttheeligiblecandidates.第11頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.5main() { floatmath,phy,chem; printf("Pleaseinputscoresofthe3subject:"); printf("Mathematics:"); scanf("%f",&math); printf("Physics:"); scanf("%f",&phy); printf("Chemistry:"); scanf("%f",&chem);

if(math>=60&&phy>=50&&chem>=40&&

(math+phy+chem>=200||math+phy>=150)) printf("Admitted!\n"); else printf("Notadmitted\n");

}第12頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.85.8Aclothshowroomhasannouncedthefollowingseasonaldiscountsonpurchaseofitems:

Writeaprogramusingswitchandifstatementstocomputethenetamounttobepaidbyacustomer.PurchaseamountDiscountMillclothHandloomitems0~100-5%101~2005%7.5%201~3007.5%10.0%Above30010.0%15.0%第13頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.8main()

{ floatprice,discount; charcategory; printf("Category(m/h):");scanf("%c",&category); printf("Price:"); scanf("%f",&price);

if(category=='m') switch((int)(price-1)/100) { case0: discount=0; break; case1: discount=0.05; break; case2: discount=0.075; break; default: discount=0.1; }

else switch((int)(price-1)/100) { case0: discount=0.05; break; case1: discount=0.075; break; case2: discount=0.1; break; default: discount=0.15; }

printf("Thenetamounttobepaidis%.2f\n",price*(1-discount));}第14頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.95.9Writeaprogramthatwillreadthevalueofxandevaluatethefollowing

using (a)nestedifstatements

(b)elseifstatements,and

(c)conditionaloperator?:第15頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.9main() /*(a)*/{ floatx; printf("Pleaseinputthevalueofx:"); scanf("%f",&x);

if(x!=0) { if(x>0) printf("y=1\n"); else printf("y=-1\n"); } else printf("y=0\n");}第16頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.9main() /*(b)*/{ floatx; printf("Pleaseinputthevalueofx:"); scanf("%f",&x);

if(x>0) printf("y=1\n"); else if(x==0) printf("y=0\n"); else printf("y=-1\n");}第17頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.9main() /*(c)*/{ floatx; printf("Pleaseinputthevalueofx:"); scanf("%f",&x);

printf("y=%d\n",x>0?1:x<0?-1:0);}第18頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.105.10Writeaprogramtocomputetherealrootsofaquadraticequation

Therootsaregivenbytheequations

Theprogramshouldrequestforthevaluesoftheconstantsa,bandcandprintthevaluesofx1,andx2.Usethefollowingrules:

(a)Nosolution,ifbothaandbarezero

(b)Thereisonlyoneroot,ifa=0(x=-c/b)

(c)Therearenorealroots,ifb2-4acisnegative (d)Otherwise,therearetworealroots Testyourprogramwithappropriatedatasothatalllogicalpathsareworkingasperyourdesign.Incorporateappropriateoutputmessages.第19頁/共104頁1/17/2023Chapter5 DecisionMakingandBranching 5.10#include<math.h>main()

{ floata,b,c,f; printf("Pleaseinputthevalueofa,bandcinthequadraticequation:\nax*x+bx+c=0\n"); printf("a="); scanf("%f",&a); printf("b="); scanf("%f",&b); printf("c="); scanf("%f",&c); printf("About%.2fx*x+%.2fx+%.2f=0:",a,b,c);

if(a==0&&b==0)printf("Thereisnosolution!\n"); else if(a==0) printf("Thereisonlyoneroot:%.2f.\n",-c/b); else { f=b*b-4*a*c; if(f<0)printf("Therearenorealroots!\n"); else printf("Thereare2realroots:%.2f,

%.2f.\n",(-b+sqrt(f))/2/a,(-b-sqrt(f))/2/a);}}第20頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.16.1Givenanumber,writeaprogramusingwhilelooptoreversethedigitsofthenumber.

Forexample,thenumber12345shouldbewrittenas54321.

(Hint:Usemodulusoperatortoextractthelastdigitandtheintegerdivisionby10togetthen-1digitnumberfromthendigitnumber.)第21頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.1main(){ longn; printf("Inputapositiveinteger:"); scanf("%ld",&n);

while(n!=0) { printf("%d",n%10);

n=n/10;/*numberisdecreasedby10times*/}}第22頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.26.2Thefactorialofanintegermistheproductofconsecutiveintegersfrom1tom.Thatis,

factorialm=m!=m×(m-1)×……×1.

Writeaprogramthatcomputesandprintsatableoffactorialsforanygivenm.第23頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.2main(){ intm;longn=1; printf("Pleaseinputanumber:"); scanf("%d",&m);

printf("%d!=",m);

while(m>=1){ n*=m; m--;}printf("%ld\n",n);}第24頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.36.3Writeaprogramtocomputethesumofthedigitsofagivenintegernumber.第25頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.3main(){ longn; intsum=0; printf("Inputapositiveinteger:"); scanf("%ld",&n);

while(n!=0) { sum=sum+n%10;

n=n/10;/*numberisdecreasedby10times*/}printf("Thesumofthedigitsis%d.\n",sum);}第26頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.46.4Thenumbersinthesequence

1123581321……

arecalledFibonaccinumbers.

Writeaprogramusingado...whilelooptocalculateandprintthefirstmFibonaccinumbers.

(Hint:Afterthefirsttwonumbersintheseries,eachnumberisthesumofthetwoprecedingnumbers.)第27頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.4main(){ longf1=1,f2=1,f=1; inti=2,m; printf("Howmanynumbersdoyouwanttooutput?"); scanf("%d",&m); printf("%12ld",f);

while(i<=m) { printf("%12ld",f); f=f1+f2; f1=f2; f2=f; if(i%4==0)printf("\n"); i++; }}第28頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.56.5RewritetheprogramoftheExample6.1usingtheforstatement.第29頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.5main(){ intcount,n; floatx,y; printf("Enterthevaluesofxandn:"); scanf("%f%d",&x,&n);

for(y=1.0,count=1;count<=n;count++) y=y*x;

printf("\nx=%f;n=%d;xtopowern=%f\n",x,n,y);}第30頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.66.6WriteaprogramtoevaluatethefollowinginvestmentequationV=P(1+r)nandprintthetableswhichwouldgivethevalueofVforvariouscombinationofthefollowingvaluesofP,randn.

P:1000,2000,3000,……,10,000 r:0.10,0.11,0.12,……,0.20 n:1,2,3,……,8(Ichangethevalueofnforformat.) (Hint:PistheprincipalamountandVisthevalueofmoneyattheendofnyears.Thisequationcanberecursivelywrittenas V=P(1+r)P=VThatis,thevalueofmoneyattheendoffirstyearbecomestheprincipalamountforthenextyearandsoon.)第31頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.6main(){ intn; floatp,pp,r,v; charch; for(p=1000;p<=10000;p=p+1000) { printf("\nPrincipalamount:%.0f\nrate",p); for(n=1;n<=8;n++) if(n==1) printf("%dyear",n); else printf("%dyears",n); for(r=0.10;r<0.21;r=r+0.01) { pp=p; printf("\n%.2f:",r); for(n=1;n<=8;n++) { v=pp*(1+r); pp=v; printf("%9.2f",v); } } printf("\nPressenterkeytocontinue..."); scanf("%c",&ch); }}第32頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.76.7Writeprogramstoprintthefollowingoutputsusingforloops.

(a) 1 (b) *****

22 **** 333 ***

4444 **

55555 *第33頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.7main() /*(a)*/{ inti,j; for(i=1;i<=5;i++) { for(j=1;j<=i;j++) printf("%d",i); printf("\n"); }}第34頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.7main() /*(b)*/{ inti,j; for(i=5;i>=1;i--) { for(j=1;j<=5-i;j++) printf(""); for(j=1;j<=i;j++) printf("*"); printf("\n"); }}第35頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.86.8Writeaprogramtoreadtheageof100personsandcountthenumberofpersonsintheagegroup50to60.

Useforandcontinuestatements.第36頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.8main() { intage,count=0,i;

for(i=1;i<=100;i++) { printf("Pleaseinputtheageofperson%d:",i); scanf("%d",&age);

if(age<50||age>60) continue; count++; } printf("Thenumberofpersonsintheagegroup50to60is%d.\n",count);}第37頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.106.9Writeaprogramtoprintatableofvaluesofthefunctiony=exp(-x)forxvaryingfrom0.0to10.0instepsof0.10.Thetableshouldappearasfollows:

TableforY=EXP(-X)

________________________________________________ x 0.1 0.2 0.3 …… 0.9 0.0 1.0 2.0 3.0 …… 9.0 ________________________________________________第38頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.10#include<math.h>main() { doublex=0; inti,j; printf("\nY=EXP(-X)\n"); for(i=1;i<=80;i++) printf("_"); printf("\nx\t"); for(i=1;i<=9;i++) printf("\t0.%d",i);

for(i=0;i<=9;i++) { printf("\n\n%d.0",i); for(j=0;j<=9;j++) { x=i+0.1*j; printf("\t%.2le",exp(-x)); } } for(i=1;i<=80;i++) printf("_"); }第39頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.116.11Writeaprogramthatwillreadapositiveintegeranddetermineandprintitsbinaryequivalent. (Hint:Thebitsofthebinaryrepresentationofanintegercanbegeneratedbyrepeatedlydividingthenumberandthesuccessivequotientsby2andsavingtheremainder,whichiseither0or1,aftereachdivision.)第40頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.11main() { longnumber,n; intm=0,i,j; printf("Pleaseinputapositivenumber:"); scanf("%ld",&number); n=number; while(n>0) {n=n/2; m++; } printf("Theequivalentbinaryof%ldis:",number);

for(i=m;i>=1;i--) { n=number; for(j=1;j<i;j++) n=n/2; printf("%ld",n%2); }}第41頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.126.12WriteaprogramusingforandifstatementtodisplaythecapitalletterSinagridof15rowsand18columnsshownbelow.***************************************************************************************************************************************************************************************************第42頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.12main() { inti,j; for(i=1;i<=15;i++) { printf("\n"); if(i>=4&&i<=6) printf("****"); else if(i>=10&&i<=12) printf("%18s","****"); else for(j=1;j<=18;j++) printf("*"); }}第43頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.136.13WriteaprogramtocomputethevalueofEuler'snumbere,thatisusedasthebaseofnaturallogarithms.Usethefollowingformula.

e=1+1/1!+1/2!+1/3!+……+1/n!

Useasuitableloopconstruct.Theloopmustterminatewhenthedifferencebetweentwosuccessivevaluesofeislessthan0.00001.第44頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.13#defineERROR0.00001main(){ floate=1,item;inti,m=1;longn; printf("e=1");

do { for(n=1,i=1;i<=m;i++) n=n*i; item=1.0/n; e=e+item; printf("+1/%d!",m); m++; }while(item>=ERROR);

printf("=%f\n",e);

}e=1+1/1!+1/2!+1/3!+1/4!+1/5!+1/6!+1/7!+1/8!+1/9!=2.718282第45頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.156.15Thepresentvalue(popularlyknownasbookvalue)ofanitemisgivenbytherelationship.P=c(1-d)n

where c=originalcost

d=rateofdepreciation(peryear)

n=numberofyears

P=presentvalueafternyears

IfPisconsideredthescrapvalueattheendofusefullifeoftheitem,writeaprogramtocomputetheusefullifeinyearsgiventheoriginalcost,depreciationrate,andthescrapvalue.Theprogramshouldrequesttheusertoinputthedatainteractively.第46頁/共104頁1/17/2023Chapter6 DecisionMakingandLooping 6.15main(){ floatc,d,p;intn,i;

printf("Theoriginalcostoftheitemis:"); scanf("%f",&c); printf("Therateofdepreciation(peryear)is:"); scanf("%f",&d); printf("Thenumberofyearsis:"); scanf("%d",&n);

for(i=1,p=c;i<=n;i++) p=p*(1–d);

printf("Thescrapvalueattheendofusefullifeoftheitemis%.2f\n",p);}第47頁/共104頁1/17/2023Chapter7 Arrays 7.37.3Anelectioniscontestedby5candidates.Thecandidatesarenumbered1to5andthevotingisdonebymarkingthecandidatenumberontheballotpaper. Writeaprogramtoreadtheballotsandcountthevotescastforeachcandidateusinganarrayvariablecount. Incase,anumberreadisoutsidetherange1to5,theballotshouldbeconsideredasa'spoiltballot'andtheprogramshouldalsocountthenumberofspoiltballots.第48頁/共104頁1/17/2023Chapter7 Arrays 7.3main(){ int count,candidate[6]={0},spoilt=0;

printf("Pleaseinputthevotes(1~5)andpress'0'toendthevoting.\n"); scanf("%d",&count); while(count) { if(count>=1&&count<=5) candidate[count]++; else spoilt++; scanf("%d",&count); } printf("Theresultofvoting:\n");

for(count=1;count<=5;count++) printf("Candidate%3d-ballots:%d\n",count,candidate[count]); printf("Spoiltballots:%d\n",spoilt);}第49頁/共104頁1/17/2023Chapter7 Arrays 7.47.4ThefollowingsetofnumbersispopularlyknownasPascal'striangle. Ifwedenoterowsbyiandcolumnsbyj,thenanyelement(excepttheboundaryelements)inthetriangleisgivenby

pi,j=pi-1,j-1+pi-1,j WriteaprogramtocalculatetheelementsofthePascaltrianglefor10rowsandprinttheresults.第50頁/共104頁1/17/2023Chapter7 Arrays 7.4#defineN10main(){ int p[N][N]={0},i,j;

for(i=0;i<N;i++) for(j=0;j<=i;j++) if(j==0||i==j) p[i][j]=1; else p[i][j]=p[i-1][j-1]+p[i-1][j];

for(i=0;i<N;i++) { for(j=0;j<=i;j++) printf("%5d",p[i][j]); printf("\n"); }}第51頁/共104頁1/17/2023Chapter7 Arrays 7.57.5Theannualexaminationresultsof100studentsaretabulatedasfollows:

Writeaprogramtoreadthedataanddeterminethefollowing: (a)Totalmarksobtainedbyeachstudent. (b)ThehighestmarksineachsubjectandtheRollNo.ofthestudentwhosecuredit. (c)Thestudentwhoobtainedthehighesttotalmarks.RollNo.Subject1Subject2Subject3第52頁/共104頁1/17/2023Chapter7 Arrays 7.5#defineN100main(){ floats[N][4]={0},m[N]={0},max; inti,j,k; printf("Pleaseinputtherollnumberandmarksof%dstudents.\n",N);

for(i=0;i<N;i++) { printf("RollNo.:"); scanf("%f",&s[i][0]); printf("ThemarkofSubjcet1:");scanf("%f",&s[i][1]);m[i]=s[i][1]; printf("ThemarkofSubjcet2:");scanf("%f",&s[i][2]);m[i]+=s[i][2]; printf("ThemarkofSubjcet3:");scanf("%f",&s[i][3]);m[i]+=s[i][3];} for(i=0;i<N;i++) printf("Totalmarksofstudent%04.0fis:%.2f\n",s[i][0],m[i]); for(j=1;j<=3;j++) { for(i=0,max=s[0][j],k=0;i<N;i++) if(s[i][j]>max){max=s[i][j]; k=i;} printf("ThehighestmarkofSubject%dis:%.2f.TheRollNo.is:

%04.0f\n",j,max,s[k][0]); } for(i=0,max=m[0],k=0;i<N;i++) if(m[i]>max){max=m[i]; k=i;} printf("Thestudent%04.0fobtainedthehighesttotalmarks.\n",s[k][0]);}第53頁/共104頁1/17/2023Chapter7 Arrays 7.67.6Givenaretwoone-dimensionalarraysAandBwhicharesortedinascendingorder.WriteaprogramtomergethemintoasinglesortedarrayCthatcontainseveryitemfromarraysAandB,inascendingorder.第54頁/共104頁1/17/2023Chapter7 Arrays 7.6#defineM5#defineN6main(){ int a[M],b[N],c[M+N],i,j,k;

printf("Input%dnumbersofarrayainascendingorder:\n",M);

for(i=0;i<M;i++) scanf("%d",&a[i]); printf("Input%dnumbersofarraybinascendingorder:\n",N); for(j=0;j<N;j++) scanf("%d",&b[j]); for(k=i=j=0;k<M+N;k++) { if(b[j]<a[i]&&j<N||i>=M) { c[k]=b[j]; j++; continue; } else { c[k]=a[i]; i++; continue; } }

printf("Themergednumbersare:"); for(k=0;k<M+N;k++) printf("%6d",c[k]);}第55頁/共104頁1/17/2023Chapter7 Arrays 7.77.7Twomatricesthathavethesamenumberofrowsandcolumnscanbemultipliedtoproduceathirdmatrix.Considerthefollowingtwomatrices.

TheproductofAandBisathirdmatrixCofsizenxnwhereeachelementofCisgivenbythefollowingequation. WriteaprogramthatwillreadthevaluesofelementsofAandBandproducetheproductmatrixC.第56頁/共104頁1/17/2023Chapter7 Arrays 7.7#defineN10main(){ int a[N][N],b[N][N],c[N][N],i,j,k;

printf("PleaseinputmatrixAof%dby%d:\n",N,N); for(i=0;i<N;i++) for(j=0;j<N;j++) scanf("%d",&a[i][j]); printf("PleaseinputmatrixBof%dby%d:\n",N,N); for(i=0;i<N;i++) for(j=0;j<N;j++) scanf("%d",&b[i][j]);

printf("TheproductofmatrixAandmatrixBis:\n");

for(i=0;i<N;i++) { for(j=0;j<N;j++) { for(k=0,c[i][j]=0;k<N;k++) c[i][j]+=a[i][k]*b[k][j]; printf("%6d",c[i][j]); } printf("\n"); }}第57頁/共104頁1/17/2023Chapter7 Arrays 7.87.8Writeaprogramthatfillsafive-by-fivematrixasfollows.Upperlefttrianglewith+1sLowerrighttrianglewith-1sRighttoleftdiagonalwithzeros Displaythecontentsofthematrixusingnotmorethantwoprintfstatements.第58頁/共104頁1/17/2023Chapter7 Arrays 7.8#defineN5main(){ int a[N][N]={0},i,j;

for(i=0;i<N;i++) for(j=0;j<N;j++) if(i+j<N-1) a[i][j]=1; else if(i+j>N-1) a[i][j]=-1;

for(i=0;i<N;i++) { for(j=0;j<N;j++) printf("%3d",a[i][j]); printf("\n"); }}第59頁/共104頁1/17/2023Chapter7 Arrays 7.97.9Selectionsortisbasedonthefollowingidea: Selectingthelargestarrayelementandswappingitwiththelastarrayelementleavesanunsortedlistwhosesizeis1lessthanthesizeoftheoriginallist.Ifwerepeatthisstepagainontheunsortedlistwewillhaveanorderedlistofsize2andanunorderedlistsizen-2.Whenwerepeatthisuntilthesizeoftheunsortedlistbecomesone,theresultwillbeasortedlist. Writeaprogramtoimplementthisalgorithm.第60頁/共104頁1/17/2023Chapter7 Arrays 7.9#defineN10main(){ inta[N],i,j,t,k; printf("Pleaseinput%dnumbers:\n",N);

for(i=0;i<N;i++)scanf("%d",&a[i]);

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

{

k=0;

for(j=1;j<=N-i;j++) if(a[k]<a[j])k=j;

t=a[k]; a[k]=a[N-i]; a[N-i]=t;

}

for(i=0;i<N;i++)printf("%d",a[i]);}第61頁/共104頁1/17/2023Chapter7 Arrays 7.107.10Developaprogramtoimplementthebinarysearchalgorithm.Thistechniquecomparesthesearchkeyvaluewiththevalueoftheelementthatismidwayina"sorted"list.Then: (a)Iftheymatch,thesearchisover. (b)Ifthesearchkeyvalueislessthanthemiddlevalue,thenthefirsthalfofthelistcontainsthekeyvalue. (c)Ifthesearchkeyvalueisgreaterthanthemiddlevalue,thenthesecondhalfcontainsthekeyvalue. Repeatthis"divide-and-conquer"strategyuntilwehaveamatch.Ifthelistisreducedtoonenon-matchingelements,thenthelistdoesnotcontainthekeyvalue.Usethesortedlistcreatedinexercise7.9oruseanyothersortedlist.第62頁/共104頁1/17/2023Chapter7 Arrays 7.10#defineN10main(){ inta[N],i,j,t,k,n,flag=0; printf("Pleaseinput%dnumbers:\n",N);

for(i=0;i<N;i++)scanf("%d",&a[i]);

for(i=1;i<N;i++) /*sorting*/ { k=0; for(j=1;j<=N-i;j++){if(a[k]<a[j])k=j;} t=a[k]; a[k]=a[N-i]; a[N-i]=t; }

for(i=0;i<N;i++)printf("%d",a[i]);

printf("Pleasethenumberyouwanttofind:"); scanf("%d",&n);

i=0; j=N-1; do { k=i+(j-i)/2; if(n==a[k]){flag=1; break;} else if(n<a[k]) j=k-1; else i=k+1; }while(i<=j); if(flag)printf("Thenumber%disontheposition%d.\n",n,i+(j-i)/2+1); else printf("Notfound!\n"); }第63頁/共104頁1/17/2023Chapter8 CharacterArraysandStrings 8.18.1Writeaprogram,whichreadsyournamefromthekeyboardandoutputsalistofASCIIcodes,whichrepresentyourname.第64頁/共104頁1/17/2023Chapter8 CharacterArraysandStrings 8.1main(){ charname[50],c; inti=0; printf("Pleaseinputyourname:");

gets(name);

printf("TheASCIIcodesrepresentingyournameis:\n");

while(name[i]!='\0')

printf("%4d",name[i++]);}第65頁/共104頁1/17/2023Chapter8 CharacterArraysandStrings 8.28.2Writeaprogramtodothefollowing: (a)Tooutputthequestion"WhoistheinventorofC?" (b)Toacceptananswer. (c)Toprintout"Good"andthenstop,iftheansweriscorrect. (d)Tooutputthemessage"tryagain",iftheansweriswrong. (e)Todisplaythecorrectanswerwhentheansweriswrongevenatthethirdattemptandstop.第66頁/共104頁1/17/2023Chapter8 CharacterArraysandStrings 8.2main(){ charname[20]="Denn

溫馨提示

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

評論

0/150

提交評論