C語言全部題目及答案_第1頁
C語言全部題目及答案_第2頁
C語言全部題目及答案_第3頁
已閱讀5頁,還剩16頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡(jiǎn)介

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

2、rwritethefirstprogram.2. Writeaprogramthatprintsthenumber1to4onthesameline.Writetheprogramusingthefollowingmethods:(a) Usingfour“printf”sfeatemen(b) Usingone“printf”statementwth/ncsionspecifier%).(c) Usingone“printf”statementwithfourconversionspecifiers(a)Writeaprogramthatcalculatesanddisplaysthenum

3、berofminutesin15days.(b) Writeaprogramthatcalculatesanddisplayshowmanyhours180minutesequalto.(c) (Optional)Howabout174minutes?ANSWERS:#include<stdio.h>#include<stdio.h>#include<stdio.h>intmain()intmain()intmain()printf("Thisismyfirstprintf("1");floatdays,minutes;prog

4、ram!");printf("2");days=15;printf("3");minutes=days*24*60;return0;printf("4");printf("Thenumberofminutesin15daysreturn0;are%fn",minutes);return0;#include<stdio.h>intmain()#include<stdio.h>#include<stdio.h>printf("Thisismysecondintma

5、in()program!");intmain()printf("1234");return0;floatminutes,hours;return0;minutes=180;#include<stdio.h>intmain()printf("%d%d%d%d",1,2,3,4);return0;hours=minutes/60;printf("180minutesequalto%fhoursn",hours);return0;#include<stdio.h>intmain()floatminutes,

6、hours;minutes=174;hours=minutes/60;printf("174minutesequalto%fhoursn",hours);return0;Exercise2:DataTypesandArithmeticOperationsYoupurchasealaptopcomputerfor$889.Thesalestaxrateis6percent.WriteandexecuteaCprogramthatcalculatesanddisplaysthetotalpurchaseprice(netprice+salestax).1. Writeaprog

7、ramthatreadsintheradiusofacircleanqbrintsthecircle'sdiameter,”.“-justtheinterestpayment.Yourprogramshouldbeabletoreproducethefollowingsamplerun:Interestcalculationprogram.Startingbalance?6000Annualinterestratepercentage?L25Balaneeafteroneyear6255ANSWER:#include<stdio.h>intmain()floatnet_pr

8、ice,sales_tax,total;net_price=889;sales_tax=net_price*0.06;total=net_price+sales_tax;printf("Thetotalpurchasepriceis%g",total);return0;#include<stdio.h>intmain()printf("Pleaseinputanumberasradius:'n");floatradius,diameter,circumference,area;scanf("%f",&rad

9、ius);printf("Thediameteris%gn",diameter=radius*2);printf("Thecircumferenceis%gn",circumference=radius*2*3.14159);printf("Theareais%gn",area=radius*radius*3.14159);return0;#include<stdio.h>intmain()floatSB,percentage,NB;printf("Interestcalculationprogram'n

10、'nPleaseentertheStartingBalance:");scanf("%f",&SB);printf("PleaseentertheAnnualinterestratepercentage:");scanf("%f",&percentage);NB=SB*percentage/100+SB;printf("nTheBalanceafteroneyearis:%g",NB);return0;Exercise3:SelectionstructureWriteaCprogr

11、amthatacceptsastuden'numericalgrade,convertsthenumericalgradetoPassed(gradeisbetween60-100),Failed(gradeisbetween0-59),orError(gradeislessthan0orgreaterthan100).1. Writeaprogramthataskstheusertoenteranintegernumber,thentellstheuserwhetheritisanoddorevennumber.2. Writeaprogramthatreadsinthreeinte

12、gersandthendeterminesandprintsthelargestinthegroup.ANSWER:#include<stdio.h>#include<stdio.h>#include<stdio.h>intmain()intgrade;intmain()inta,b,c;printf("Pleaseenter3integernumbersn");printf("Pleaseenterthegrade:");scanf("%d",&grade);printf("Th

13、enI'lltellyouwhichisthelargestn");scanf("%d%d%d",&a,&b,&c);if(a>b&&a>c)if(grade>=60&&grade<=100)printf("Passed.");elseif(grade>=0&&grade<60)printf("Failed.");elseprintf("Error.");printf("%dist

14、helargest",a);elseif(b>a&&b>c)printf("%disthelargest",b);elseif(c>a&&c>b)printf("%disthelargest",c);elseprintf("They'reequal");return0;return0;#include<stdio.h>intmain()inta;printf("Pleaseenteranintegernumbern");print

15、f("ThenI'lltellyouwhetherit'sanoddorevennumber");scanf("%d",&a);if(a%2=0)printf("%disanevennumber",a);elseprintf("%disaoddnumber",a);return0;Exercise4:switchstatementandsimplewhile”repetitionstatement1. Writeaprogramthatreadsthreeintegersanabbrevia

16、teddate(forexample:261294)andthatwillprintthedateinfull;forexample:26thDecember1994.Thedayshouldbefollowedbyanappropriatesuffix,'st','nd','rd'switch'thsfatemeetatleastoneWriteaCprogramthatusesawhilelooptocalculateandprintthesumoftheevenintegersfrom2to30.2. Alargechemicalc

17、ompanypaysitssalesstaffonacommissionbasis.Theyreceive200perweekplus9%oftheirgrosssalesforthatweek.Forexample,someonewhosells5000dfchemicalsinoneweekwillearn200plus9%of5000,atotalof650.DdvelopaCprogramthatwillinputeachsalespersongalesforProcessoneperson'sfiguresatatime.Entersalesinpounds(-1toend)

18、:5000.00Salaryis:650.00Entersalesinpounds(-1toend):00.00Salaryis:200.00Entersalesinpounds(-1toend):1088.89Salaryis:298.00Entersalesinpounds(-1toend):-1Optional:3. Amailordercompanysellsfivedifferentfollowingtable:ProductNumber1thepreviousweek,ductswhoseretailpricesareshowni

19、ntheRetailPrice(inpounds)2.984.5029.983WriteaCprogramthatreadsinaseriesofpairsofnumbersasfollows:(1) .Productnumber.QuantitysoldforonedayYourprogramshoulduseaswitchstatementtohelpdeterminetheretailpriceforeachproduct,andshoulduseasentinel-controlledlooptocalculatethetotalretailvalueofallproductssold

20、inagivenweek(7days).ANSWER:#include<stdio.h>intmain()printf("Pleaseenterthreenumbersfordate:");intday,month,year;scanf("%d%d%d",&day,&month,&year);if(day>31)printf("Error");elseswitch(day)case1:printf("1st");break;case2:printf("2nd&qu

21、ot;);break;case3:printf("3rd");break;case21:printf("21st");break;case22:printf("22nd");break;case23:printf("23rd");break;case31:printf("31st");break;default:printf("%dth",day);#include<stdio.h>intmain()inta,b;a=0;b=2;while(b<=30)a=

22、a+b;b=b+2;printf("Thesumoftheevenintegersfrom2to30is%d",a);return0;switch(month)case1:printf("January");#include<stdio.h>break;intmain()case2:printf("February");break;floata,b;case3:printf("March");break;while(a>0)case4:printf("April");break

23、;printf("Entersalesinpounds(-1tocase5:printf("May");end):");break;scanf("%f",&a);case6:printf("June");b=200+a*0.09;break;if(a=-1)case7:printf("July");printf("");break;elseprintf("Salaryis%.0fn",b);case8:printf("August&quo

24、t;);break;case9:printf("September");break;case10:printf("October");return0;break;case11:printf("November");break;case12:printf("December");break;printf("19%d",year);return0;Exercise5:forahddowhile”repetitionstatements1. Writeaprogramwhichusesado/whil

25、elooptoprintoutthefirst10powersof2otherthan0(ie.itprintsoutthevaluesof幺,22,.,210).Useaforlooptodothesame.2. Theconstantcanbecalculatedbytheinfiniteseries:=4-4/3+4/5-4/7+4/9-4/11+.WriteaCprogramthatusesado/whilelooptocalculateusingtheseries.Theprogramshouldasktheuserhowmanytermsintheseriesshouldbeuse

26、d.Thusiftheuserenters'3',thentheprogramshotddcaScbeing4-4/3+4/5.NestedrepetitionWriteaprogramthatprintsthefollowingdiamondshape.Youmayuseprintfstatementsthatprinteitherasingleasterisk(*)orasingleblank.Maximizeyouruseofrepetition(withnestedforstatements)andminimizethenumberofprintfstatements.

27、*3. Writeaprogramtoprintatableasfollows:1*1=12*1=22*1=22*2=43*1=33*2=63*3=93*1=33*2=63*3=99*1=99*2=189*3=279*4=369*5=459*6=549*7=639*8=729*9=81#include<stdio.h>#include<stdio.h>#include<stdio.h>intmain()intmain()intmain()doublec,pie,p;inta,b;inta,b,d,n;introw,a,b,j;a=0;printf("

28、;Enterterms:");row=1;b=1;scanf("%d",&a);j=4;doprintf("Pie=");while(row<=5)n=1;p=0;for(a=j;a>=1;a=a-1)a+;while(n<=a)printf("");b=b*2;for(b=1;b<=9-2*j;b+)printf("%d",b);if(n%2=0)printf("*");b=-1;for(a=j;a>=1;a=a-1)while(a<=9)

29、;elseprintf("");return0;b=1;printf("n");pie=(4.0*b)/(2.0*n-1.0);row+;#include<stdio.h>d=2*n-1;ANSWER:intmain()p=p+pie;if(n>1&&n<=a)inta;if(n%2!=0)row=1;for(a=2;a<=1024;a=a*2)printf("+");j=1;printf("%d",a);elseprintf("-");while(

30、row<=5)for(a=1;a<=j;a=a+1)return0;printf("4/%d",d);printf("");n+;for(b=1;b<=9-2*j;b+)printf("*");printf("n=%f",p);for(a=1;a<=j;a=a+1)return0;printf("");printf("n");row+;j+;return0;#include<stdio.h>intmain()inti,j;for(i=1;i

31、<=9;i+)for(j=1;j<=9;j+)if(i>=j)printf("%1d*%1d=%2d",i,j,i*j);printf("n");getchar();return0;Exercise6:SimpleFunctionsWriteaCprogramthatreadsseveralnumbersandusesthefunctionround_to_nearesttoroundeachofthesenumberstothenearestinteger.Theprogramshouldprintboththeoriginalnum

32、berandtheroundednumber.1. Writeaprogramthatreadsthreepairsofnumbersandaddsthelargerofthefirstpair,thelargerofthesecondpairandthelargerofthethirdpair.Useafunctiontoreturnthelargerofeachpair.2. Acarparkchargesa盤.00minimumfeetoparkforupto3hours,andanadditional如50foreachhourorparthourinexcessofthreehour

33、s.Themaximumchargeforanygiven24-hourperiodis£0.00.Assumethatnocarparksformorethan24hoursatatime.WriteaCprogramthatwillcalculateandprinttheparkingchargesforeachof3customerswhoparkedtheircarinthecarparkyesterday.Theprogramshouldacceptasinputthenumberofhoursthateachcustomerhasparked,andoutputthere

34、sultsinaneattabularform,alongwiththetotalreceiptsfromthethreecustomers:CarHoursCharge12todeterminetheTOTAL29.514.50Theprogramshouldusethefunctioncalculate_chargeschargeforeachcustomer.ANSWER:#include<stdio.h>#include<stdio.h>#include<math.h>intmain()intmain()floatlarger_Number(floa

35、t,float);voidround_to_nearest(float);floatnum1,num2,total=0;floatnum;inta=0;while(5)while(a<3)printf("Pleaseinputanumber:");scanf("%f",&num);printf("Pleaseinputtwonumbers:");scanf("%f%f",&num1,&num2);round_to_nearest(num);total=total+larger_Numb

36、er(num1,num2);return0;a=a+1;voidround_to_nearest(floatnuml)intnear_integer;intsmall_integer=floor(numl);if(num1-small_integer>=0.5)near_integer=ceil(numl);elsenear_integer=floor(numl);printf("nThenearestintegerofthenumberis:%dn",near_integer);_voidround_to_nearest(floatnuml)intnear_inte

37、ger;intsmall_integer=floor(numl);if(num1-small_integer>=0.5)near_integer=ceil(numl);elsenear_integer=floor(numl);printf("nThenearestintegerofthenumberis:%dn",near_integer);_printf("nThetotalis%f",total);return0;floatlarger_Number(floatnum1,floatnum2)_floatlarger;if(num1>=nu

38、m2)printf("%f",num1);larger=num1;elseprintf("%f",num2);larger=num2;printf("n");return(larger);#include<stdio.h>intmain()floatcalculate_charges(float);floathour1,hour2,hour3,charge1,charge2,charge3,total1=0,total2=0;printf("Pleaseinputthreecar'sparkinghour

39、s:");scanf("%f%f%f",&hour1,&hour2,&hour3);charge仁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)

40、;printf("3%10.1f%10.2fn",hour3,charge3);total仁hour1+hour2+hour3;total2=charge1+charge2+charge3;printf("TOTAL%7.2f%9.2f",total1,total2);return0;floatcalculate_charges(floathour)_floatcharge;if(hour<=3)charge=2;if(hour>3&&hour<=19)charge=2.+0.50*(hour-3.);if(hour&g

41、t;19&&hour<=24)charge=10;return(charge);Exercise7:MoreFunctionsWriteaprogramthatusessentinel-controlledrepetitiontotakeanintegerasinput,andpassesittoafunctionevenwhichusesthemodulusoperatortodetermineiftheintegeriseven.Thefunctionevenshouldreturn1iftheintegeriseven,and0ifitisnot.Theprogra

42、mshouldtakethevaluereturnedbythefunctionevenanduseittoprintoutamessageannouncingwhetherornottheintegerwaseven.1. WriteaCprogramthatusesthefunctiorintegerPower1(base,exponent)toreturnthevalueof:basxponentsothat,forexample,integerPower1(3,4)givesthevalue3*3*3*3.Assumethatexponentisapositive,non-zeroin

43、teger,andbaseisaninteger.Thefunctionshoulduseaforloop,andmakenocallstoanymathlibraryfunctions.2. WriteaCprogramthatusestherecursivefunctionintegerPower2(base,exponent)toreturnthevalueof:basxponentsothat,forexamplentegerPower2(3,4)givesthevalue3*3*3*3.Assumethatexponentisapositive,non-zerointeger,and

44、baseisaninteger.Thefunctionshouldmakenocallstoanymathlibraryfunctions.(Hint:therecursivestepwillusetherelationship:basxponent=base.bas§xponent-11andthebasecasewillbewheiexponentis1since:base=base.)ANSWER:#include<stdio.h>intmain()inta,b;intjudge(int);voidjudge1(int);printf("Pleaseent

45、eranumber");scanf("%d",&a);while(a>=-1)b=judge(a);judge1(b);printf("Pleaseevteranumber");scanf("%d",&a);return0;#include<stdio.h>intmain()intintegerPower2(int,int);intbase,exponent,result;printf("Thisprogramcancalculatethepowern");printf(

46、"Enteraintegerbasenumber:n");scanf("%d",&base);printf("Enteranon-zerointegernumberastheexponent:n");scanf("%d",&exponent);result=integerPower2(base,exponent);printf("Thepoweris:%d",result);return0;intintegerPower2(intx,inty)if(y=1)intjudge(in

47、tx)return(x);if(x%2!=0)elsereturn(0);return(x*integerPower2(x,y-1);elsereturn(1);voidjudge1(intx)#include<stdio.h>if(x=1)intmain()printf("It'sevenn");elseintintegerPower1(int,int);printf("It'soddn");intbase,exponent,answer;printf("Letuscalculatethepowern")

48、;printf("Pleaseenteraintegerbasenumber:n");scanf("%d",&base);printf("Pleaseenteranon-zerointegernumberastheexponent:n");scanf("%d",&exponent);answer=integerPower1(base,exponent);printf("Sothepoweris:%d",answer);return0;intintegerPower1(intx,i

49、nty)inti,a;a=1;for(i=1;i<=y;i+)a=x*a;return(a);Exercise08:ArraysWriteaprogramthatreadstennumberssuppliedbytheuserintoasinglesubscriptedarray,andthenprintsouttheaverageofthem.1. Writeaprogramthatreadstennumberssuppliedbytheuserintoa2by5array,andthenprintsoutthemaximumandminimumvaluesheldin:(a) eac

50、hrow(2rows)(b) thewholearrayUseasingle-subscriptedarraytosolvethefollowingproblem.Readin20numbers,eachofwhichisbetween10and100,inclusive.Aseachnumberisread,printitonlyifitisnotaduplicateofanumberalreadyread.Preparefortheworstcase"inwhichall20numbersaredifferent.Usethesmallestpossiblearraytosolv

51、ethisproblem.#include<stdio.h>intmain()#defineMAXGRADES10intgradesMAXGRADES;inti,total=0;floataverage;#include<stdio.h>intmain()#defineMAXNUM5intnumberMAXNUM;inti,j,a;printf("Pleaseenter5numbersbetween10and100n");printf("Enteranumber:");scanf("%d",&grade

52、si);printf("nTheaverageofthenumbersn");for(i=0;i<MAXGRADES;i+)printf("%d",gradesi);total+=gradesi;average=total/10.0;printf("is%fn"average);return0;for(i=0;i<MAXNUM;i+)scanf("%d",&numberi);a=0;for(i=0;i<MAXNUM;i+)for(j=0;j<i;j+)if(numberi=numbe

53、rj)a+;if(a=0)printf("%d",numberi);a=0;return0;ANSWER:#include<stdio.h>intmain()#defineNUMROWS2#defineNUMCOLS5intnumberNUMROWSNUMCOLS;inti,j,max1,max2,min1,min2;for(i=O;i<NUMROWS;i+)printf("Pleaseinput5numberswithspacebetweeneachother:'n");for(j=O;j<NUMCOLS;j+)scan

54、f("%d",&numberij);max仁number00;min仁number00;max2=number10;min2=number10;for(j=0;j<NUMCOLS;j+)if(number0j>=max1)max仁number0j;if(number0j<=min1)min仁number0j;if(number1j>=max2)max2=number1j;if(number1jv=min2)min2=number1j;printf("Themaxofthefirstrowis%dn",max1);print

55、f("Theminofthefirstrowis%dn",min1);printf("Themaxofthesecondrowis%dn",max2);printf("Theminofthesecondrowis%dn",min2);printf("Themaxoftworowsis");if(max1>=max2)printf("%dn",max1);elseprintf("%dn",max2);printf("Theminoftworowsis"

56、);if(min1<=min2)printf("%dn",min1);elseprintf("%dn",min2);return0;Exercise9:MoreArrays1. Writeaprogramthatenters5namesoftownsandtheirrespectivedistanee(aninteger)fromLondoninmiles.Theprogramwillprintofthenamesofthetownsthatarelessthan100milesfromLondon.Usearraysandcharacterstr

57、ingstoimplementyourprogram.2. Writeaprogramthatpromptstheusertotypeinfourcharacterstrings,placestheseinanarrayofstrings,andthenprintsout:(e.g.IamPeterPan)(i) Thefourstringsinreverseorder.(e.g.PanPeteramI)(ii) Thefourstringsintheoriginalorder,butwitheachstringbackwards.(e.g.ImaretePnaP)(iii) Thefours

58、tringsinreverseorderwitheachstringbackwards.(e.g.naPretePmaI)#include<stdio.h>intmain()charcharacter20;intinteger5;inti;for(i=0;i<5;i+)printf("Pleaseenteranameofatown:n”);seanf("%s",characteri);printf("EnteritsdistaneefromLondoninmiles:n");seanf("%d",&

59、integeri);printf("Thetownsthatarelessthan100milesfromLondonare:n");for(i=0;i<5;i+)if(integeri<100)printf("%s",characteri);return0;/PanPeteramI#include<stdio.h>intmain()charfour481;inti;printf("Pleaseinputfourwords:n");for(i=0;i<4;i+)scanf("%s",f

60、ouri);printf("Thefourstringsinreverseorderis:n");for(i=3;i>=0;i-)printf("%s",fouri);return0;naPretePmaI#include<stdio.h>intmain()charfour481;inti,j;printf("Pleaseinputfourwords:n")for(i=0;i<4;i+)scanf("%s",fouri);printf("Thefourstringsare:n&qu

61、ot;);for(i=3;i>=0;i-)for(j=0;fourij!='0'j+);for(j=j-1;j>=0;j-)printf("%c",fourij);printf("");return0;naPretePmaI#include<stdio.h>intmain()charfour481;inti,j;printf("Pleaseinputfourwords:n")for(i=0;i<4;i+)scanf("%s",fouri);printf("Thefourstringsare:n");for(i=3;i>=0;i-)for(j=0;fourij!='0'j+);for(j=j-1;j>=0;j-)printf("%c",fourij);printf("");return0;Exercise10:PointersWriteaprogramthatreads5integersintoanarra

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(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)論