C语言全部题目及答案_第1页
C语言全部题目及答案_第2页
C语言全部题目及答案_第3页
C语言全部题目及答案_第4页
C语言全部题目及答案_第5页
免费预览已结束,剩余16页可下载查看

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、C语言全部题目及答案Exercise1:ProgrammingEnvironmentandBasicInput/Output1. Writeaprogramthatprints“Thisismyfirstprogram!”onthescreen.(a)Savethisprogramontoyourowndiskwiththenameofe2-1a;(b)RunthisprogramwithoutopeningTurboC;(c)Modifythisprogramtoprint“Thisismysecondprogram!”,thensaveitase2-1b.Pleasedonotoverwr

2、itethefirstprogram.2. Writeaprogramthatprintsthenumber1to4onthesameline.Writetheprogramusingthefollowingmethods:(a) Usingfour“printfstatements.(b) Usingone“printf“statementwithnoconversionspecifier(i.e.no%).(c) Usingone“printf“statementwithfourconversionspecifiers3. (a)Writeaprogramthatcalculatesand

3、displaysthenumberofminutesin15days.(b) Writeaprogramthatcalculatesanddisplayshowmanyhours180minutesequalto.(c) (Optional)Howabout174minutes?ANSWERS:#include#include#includeintmain()intmain()intmain()printf(Thisismyprintf(1);floatfirstprogram!);printf(2);days,minutes;return0;printf(3);days=15;printf(

4、4);minutes=days*24#includereturn0;*60;intmain()printf(Thenumber#includeofminutesin15printf(Thisismyintmain()daysare%fn,secondprogram!);(minutes);return0;printf(1234);return0;)return0;)#include#includeintmain()intmain()(floatprintf(%d%d%d%d,1,minutes,hours;2,3,4);minutes=180;return0;hours=minutes/)60

5、;printf(180minutesequalto%fhoursn,hours);return0;)#includeintmain()(floatminutes,hours;minutes=174;hours=minutes/60;printf(174minutesequalto%fhoursn,hours);return0;)Exercise2:DataTypesandArithmeticOperations1. Youpurchasealaptopcomputerfor$889.Thesalestaxrateis6percent.WriteandexecuteaCprogramthatca

6、lculatesanddisplaysthetotalpurchaseprice(netprice+salestax).2. Writeaprogramthatreadsintheradiusofacircleandprintsthecirclesdiameter,circumferenceandarea.Usethevalue3.14159for“.3. Writeaprogramthatreadsintwonumbers:anaccountbalanceandanannualinterestrateexpressedasapercentage.Yourprogramshouldthendi

7、splaythenewbalanceafterayear.Therearenodepositsorwithdrawsjusttheinterestpayment.Yourprogramshouldbeabletoreproducethefollowingsamplerun:Interestcalculationprogram.Startingbalance?6000Annualinterestratepercentage?4.25Balanceafteroneyear:6255ANSWER:#includeintmain()floatnet_price,sales_tax,total;net_

8、price=889;sales_tax=net_price*0.06;total=net_price+sales_tax;printf(Thetotalpurchasepriceis%g,total);return0;)#includeintmain()(printf(Pleaseinputanumberasradius:n);floatradius,diameter,circumference,area;scanf(%f,&radius);printf(Thediameteris%gn”,diameter=radius*2);printf(Thecircumferenceis%gn,circ

9、umference=radius*2*3.14159);printf(Theareais%gn,area=radius*radius*3.14159);return0;)#includeintmain()(floatSB,percentage,NB;printf(InterestcalculationprogramnnPleaseentertheStartingBalance:);scanf(%f,&SB);printf(PleaseentertheAnnualinterestratepercentage:);scanf(%f,&percentage);NB=SB*percentage/100

10、+SB;printf(nTheBalanceafteroneyearis:%g,NB);return0;)Exercise3:Selectionstructure1. WriteaCprogramthatacceptsastudentsnumericalgrade,convertsthenumericalgradetoPassed(gradeisbetween60-100),Failed(gradeisbetween0-59),orError(gradeislessthan0orgreaterthan100).2. Writeaprogramthataskstheusertoenteranin

11、tegernumber,thentellstheuserwhetheritisanoddorevennumber.3. .Writeaprogramthatreadsinthreeintegersandthendeterminesandprintsthelargestinthegroup.ANSWER:#include#include#includeintmain()(intgrade;printf(Pleaseenterthegrade:);scanf(%d”,&grade);if(grade=60&grade=0&grade60)printf(Failed.);elseprintf(Err

12、or.);return0;#includeintmain()(inta,b,c;printf(Pleaseenter3numbersn);printf(ThenIlltellyouwhichisthelargestn);scanf(%d%d%d,&a,&b,&c);if(ab&ac)printf(%disthelargest,a);elseif(ba&bc)printf(%disthelargest,b);elseif(ca&cb)printf(%disthelargest,c);elseprintf(Theyreequal);return0;integerintmain()(inta;pri

13、ntf(Pleaseenteranintegernumbern);printf(ThenIlltellyouwhetheritsanoddorevennumber);scanf(%d,&a);if(a%2=0)printf(%disanevennumber,a);elseprintf(%disaoddnumber,a);return0;Exercise4:switchstatementandsimple“whilerepetitionstatement1.VMteaprogramthatreadsthreeintegersanabbreviateddate(forexample:261294)

14、andthatwillprintthedateinfull;forexample:26thDecember1994.Thedayshouldbefollowedbyanappropriatesuffix,41.stnd,rdorth.Useatleastoneswitchstatement.2. WriteaCprogramthatusesawhilelooptocalculateandprintthesumoftheevenintegersfrom2to30.3. Alargechemicalcompanypaysitssalesstaffonacommissionbasis.Theyrec

15、eive200perweekplus9%oftheirgrosssalesforthatweek.Forexample,someonewhosells5000ofchemicalsinoneweekwillearn200plus9%of55000,atotalof650.DevelopaCprogramthatwillinputeachsalespersonssalesforthepreviousweek,andprintouttheirsalary.Processonepersonsfiguresatatime.Entersalesinpounds(-1toend):5000.00Salar

16、yis:650.00Entersalesinpounds(-1toend):00.00Salaryis:200.00Entersalesinpounds(-1toend):1088.89Salaryis:298.00Entersalesinpounds(-1toend):-1Optional:4. Amailordercompanysellsfivedifferentproductswhoseretailpricesareshowninthefollowingtable:ProductNumberRetailPrice(inpounds)1 2.982 4.503 9.984 4.495 6.

17、87WriteaCprogramthatreadsinaseriesofpairsofnumbersasfollows:(1) .Productnumber(2) .QuantitysoldforonedayYourprogramshoulduseaswitchstatementtohelpdeterminetheretailpriceforeachproduct,andshoulduseasentinel-controlledlooptocalculatethetotalretailvalueofallproductssoldinagivenweek(7days).ANSWER:#inclu

18、deintmain()printf(Pleaseenterthreenumbersfordate:);intday,month,year;scanf(%d%d%d,&day,&month,&year);if(day31)printf(Error);elseswitch(day)case1:printf(1st);break;case2:printf(2nd);break;case3:printf(3rd);break;case21:printf(21st);break;case22:printf(22nd);break;case23:printf(23rd);break;case31:prin

19、tf(31st);break;default:printf(%dth,day);switch(month)#includeintmain()inta,b;a=0;b=2;while(b=30)a=a+b;b=b+2;printf(Thesumoftheevenintegersfrom2to30is%d,a);return0;#includeintmain()floata,b;while(a0)printf(Entersalesinpounds(-1toend):);scanf(%f,&a);b=200+a*0.09;if(a=-1)printf();elseprintf(Salaryis%.0

20、fn,b);return0;(case 1: printf(January);break;case 2: printf(February);break;case 3: printf(March);break;case 4: printf(April);break;case 5: printf(May);break;case 6: printf(June);break;case 7: printf(July);break;case 8: printf(August);break;case 9: printf(September);break;case 10: printf(October);br

21、eak;case 11: printf(November);break;case 12: printf(December);break;)printf(19%d,year);return0;)Exercise5:foranddowhilerepetitionstatements1. Writeaprogramwhichusesado/whilelooptoprintoutthefirst10powersof2otherthan0(ie.itprintsoutthevaluesof21,22,.,210).Useaforlooptodothesame.2. Theconstant:canbeca

22、lculatedbytheinfiniteseries:=4-4/3+4/5-4/7+4/9-4/11+.WriteaCprogramthatusesado/whilelooptocalculate:usingtheseries.Theprogramshouldasktheuserhowmanytermsintheseriesshouldbeused.Thusiftheuserenters3,thentheprogramshouldcalculate?asbeing4-4/3+4/5.Nestedrepetition3. Writeaprogramthatprintsthefollowingd

23、iamondshape.Youmayuseprintfstatementsthatprinteitherasingleasterisk(*)orasingleblank.Maximizeyouruseofrepetition(withnestedforstatements)andminimizethenumberofprintfstatements.*1*1=14. Writeaprogramtoprintatableasfollows:2*1=22*2=43*1=33*2=63*3=99*1=99*2=189*3=279*4=369*5=459*6=549*7=639*8=729*9=81A

24、NSWER:#includeintmain()inta,b;a=0;b=1;doa+;b=b*2;printf(%d,b);while(a=9);return0;#includeintmain()inta;for(a=2;a=1024;a=a*2)printf(%d,a);return0;#includeintmain()doublec,pie,p;inta,b,d,n;printf(Enterterms:);scanf(%d,&a);printf(Pie=);n=1;p=0;while(n1&n=a)if(n%2!=0)printf(+);elseprintf(-);#includeintm

25、ain()introw,a,b,j;row=1;j=4;while(row=1;a=a-1)printf();for(b=1;b=1;a=a-1)printf();printf(n);row+;j-;row=1;j=1;while(row=5)for(a=1;a=j;a=a+1)printf();for(b=1;b=9-2*j;b+)printf(*);printf(4/%d,d);n+;printf(n=%f,p);return0;for(a=1;a=j;a=a+1)printf();printf(n);row+;j+;return0;#includeintmain()(inti,j;for

26、(i=1;i=9;i+)(for(j=1;j=j)printf(%1d*%1d=%2d,i,j,i*j);printf(n);getchar();return0;Exercise6:SimpleFunctions1. WriteaCprogramthatreadsseveralnumbersandusesthefunctionround_to_nearesttoroundeachofthesenumberstothenearestinteger.Theprogramshouldprintboththeoriginalnumberandtheroundednumber.2. Writeaprog

27、ramthatreadsthreepairsofnumbersandaddsthelargerofthefirstpair,thelargerofthesecondpairandthelargerofthethirdpair.Useafunctiontoreturnthelargerofeachpair.3. Acarparkchargesa22.00minimumfeetoparkforupto3hours,andanadditional0.50foreachhourorparthourinexcessofthreehours.Themaximumchargeforanygiven24-ho

28、urperiodis10.00.Assumethatnocarparksformorethan24hoursatatime.WriteaCprogramthatwillcalculateandprinttheparkingchargesforeachof3customerswhoparkedtheircarinthecarparkyesterday.Theprogramshouldacceptasinputthenumberofhoursthateachcustomerhasparked,andoutputtheresultsinaneattabularform,alongwiththetot

29、alreceiptsfromthethreecustomers:CarHoursCharge1 1.52.002 4.02.503 24.010.00TOTAL29.514.50Theprogramshouldusethefunctioncalculate_chargestodeterminethechargeforeachcustomer.ANSWER:#include#includeintmain()voidround_to_nearest(float);floatnum;while(5)printf(Pleaseinputanumber:);scanf(%f,&num);round_to

30、_nearest(num);一一return0;voidround_to_nearest(floatnum1)intnear_integer;intsmall_integer=floor(num1);if(num1-small_integer=0.5)near_integer=ceil(num1);elsenear_integer=floor(num1);printf(nThenearestintegerofthenumberis:%dn,near_integer);.#includeintmain()floatlarger_Number(float,float);floatnum1,num2

31、,total=0;inta=0;while(a=num2)printf(%f,num1);larger=num1;elseprintf(%f,num2);larger=num2;printf(n);return(larger);#includeintmain()(floatcalculate_charges(float);floathour1,hour2,hour3,charge1,charge2,charge3,total1=0,total2=0;printf(Pleaseinputthreecarsparkinghours:);scanf(%f%f%f,&hour1,&hour2,&hou

32、r3);charge1=calculate_charges(hour1);charge2=calculate_charges(hour2);charge3=calculate_charges(hour3);printf(CarHoursChargen);printf(1%10.1f%10.2fn,hour1,charge1);printf(2%10.1f%10.2fn,hour2,charge2);printf(3%10.1f%10.2fn,hour3,charge3);total1=hour1+hour2+hour3;total2=charge1+charge2+charge3;printf

33、(TOTAL%7.2f%9.2f,total1,total2);return0;)floatcalculate_charges(floathour)(floatcharge;if(hour3&hour19&hour=24)charge=10;return(charge);)Exercise7:MoreFunctions1. Writeaprogramthatusessentinel-controlledrepetitiontotakeanintegerasinput,andpassesittoafunctionevenwhichusesthemodulusoperatortodetermine

34、iftheintegeriseven.Thefunctionevenshouldreturn1iftheintegeriseven,and0ifitisnot.Theprogramshouldtakethevaluereturnedbythefunctionevenanduseittoprintoutamessageannouncingwhetherornottheintegerwaseven.2. WriteaCprogramthatusesthefunctionintegerPower1(base,exponent)toreturnthevalueof:,exponentbase产soth

35、at,forexample,integerPower1(3,4)givesthevalue3*3*3*3. Assumethatexponentisapositive,non-zerointeger,andbaseisaninteger.Thefunctionshoulduseaforloop,andmakenocallstoanymathlibraryfunctions.3.WriteaCprogramthatusestherecursivefunctionintegerPower2(base,exponent)toreturnthevalueof:baseexponentsothat,fo

36、rexample,integerPower2(3,4)givesthevalue3*3*3*3.Assumethatexponentisapositive,non-zerointeger,andbaseisaninteger.Thefunctionshouldmakenocallstoanymathlibraryfunctions.(Hint:therecursivestepwillusetherelationship:baseexponent_basebaseexponent-1andthebasecasewillbewhenexponentis1since:base1=base.)ANSW

37、ER:#includeintmain()(inta,b;intjudge(int);voidjudge1(int);printf(Pleaseenteranumber);scanf(%d,&a);while(a=-1)(b=judge(a);judge1(b);printf(Pleaseevteranumber);scanf(%d,&a);return0;intjudge(intx)(if(x%2!=0)return(0);elsereturn(1);voidjudge1(intx)(if(x=1)printf(Itsevenn);elseprintf(Itsoddn);#includeint

38、main()(intintegerPower2(int,int);intbase,exponent,result;printf(Thisprogramcancalculatethepowern);printf(Enteraintegerbasenumber:n);scanf(%d,&base);printf(Enteranon-zerointegernumberastheexponent:n);scanf(%d,&exponent);result=integerPower2(base,exponent);printf(Thepoweris:%d,result);return0;intinteg

39、erPower2(intx,inty)(if(y=1)return(x);elsereturn(x*integerPower2(x,y-1);#includeintmain()(intintegerPower1(int,int);intbase,exponent,answer;printf(Letuscalculatethepowern);printf(Pleaseenteraintegerbasenumber:n);scanf(%d,&base);printf(Pleaseenteranon-zerointegernumberastheexponent:n);scanf(%d,&expone

40、nt);answer=integerPower1(base,exponent);printf(Sothepoweris:%d,answer);return0;intintegerPower1(intx,inty)(inti,a;a=1;for(i=1;i=y;i+)a=x*a;return(a);)Exercise08:Arrays1. Writeaprogramthatreadstennumberssuppliedbytheuserintoasinglesubscriptedarray,andthenprintsouttheaverageofthem.2. Writeaprogramthat

41、readstennumberssuppliedbytheuserintoa2by5array,andthenprintsoutthemaximumandminimumvaluesheldin:(a)eachrow(2rows)(b)thewholearray3. Useasingle-subscriptedarraytosolvethefollowingproblem.Readin20numbers,eachofwhichisbetween10and100,inclusive.Aseachnumberisread,printitonlyifitisnotaduplicateofanumbera

42、lreadyread.Prepareforthe“worstcaseinwhichall20numbersaredifferent.Usethesmallestpossiblearraytosolvethisproblem.#includeintmain()(#defineMAXGRADES10intgradesMAXGRADES;inti,total=0;floataverage;for(i=0;iMAXGRADES;i+)printf(Enteranumber:);scanf(%d”,&gradesi);)printf(nTheaverageofthenumbersn);for(i=0;i

43、MAXGRADES;i+)printf(%d,gradesi);total+=gradesi;)average=total/10.0;printf(is%fn,average);return0;#includeintmain()#defineMAXNUM5intnumberMAXNUM;inti,j,a;printf(Pleaseenter5numbersbetween10and100n);for(i=0;iMAXNUM;i+)scanf(%d,&numberi);a=0;for(i=0;iMAXNUM;i+)for(j=0;ji;j+)if(numberi=numberj)a+;if(a=0

44、)printf(%d,numberi);a=0;return0;ANSWER:#includeintmain()#defineNUMROWS2#defineNUMCOLS5intnumberNUMROWSNUMCOLS;inti,j,max1,max2,min1,min2;for(i=0;iNUMROWS;i+)printf(Pleaseinput5numberswithspacebetweeneachother:n);for(j=0;jNUMCOLS;j+)scanf(%d”,&numberij);max1=number00;min1=number00;max2=number10;min2=

45、number10;for(j=0;j=max1)max1=number0j;if(number0j=max2)max2=number1j;if(number1j=max2)printf(%dn,max1);elseprintf(%dn,max2);printf(Theminoftworowsis);if(min1=min2)printf(%dn,min1);elseprintf(%dn,min2);return0;)Exercise9:MoreArrays1. Writeaprogramthatenters5namesoftownsandtheirrespectivedistance(anin

46、teger)fromLondoninmiles.Theprogramwillprintofthenamesofthetownsthatarelessthan100milesfromLondon.Usearraysandcharacterstringstoimplementyourprogram.2. Writeaprogramthatpromptstheusertotypeinfourcharacterstrings,placestheseinanarrayofstrings,andthenprintsout:(e.g.IamPeterPan)(i) Thefourstringsinrever

47、seorder.(e.g.PanPeteramI)(ii) Thefourstringsintheoriginalorder,butwitheachstringbackwards.(e.g.ImaretePnaP)(iii) Thefourstringsinreverseorderwitheachstringbackwards.(e.g.naPretePmaI)#includeintmain()charcharacter520;intinteger5;inti;for(i=0;i5;i+)printf(Pleaseenteranameofatown:n);scanf(%s,characteri

48、);printf(EnteritsdistancefromLondoninmiles:n);scanf(%d”,&integeri);)printf(Thetownsthatarelessthan100milesfromLondonare:n);for(i=0;i5;i+)if(integeri100)printf(%s,characteri);)return0;/PanPeteramI#includeintmain()charfour481;/naPretePmaI#includeintmain()charfour481;inti;printf(Pleaseinputfourwords:n);for(i=0;i=0;i-)printf(%s,fouri);return0;inti,j;printf(Pleaseinputfourwords:n);for(i=0;i=0;i-)for(j=0;fourij!=0;j+);for(j=j-1;j=0;j-)printf(%c,fourij);printf();return0;E

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论