《大学C程序设计教程》例题源码_第1页
《大学C程序设计教程》例题源码_第2页
《大学C程序设计教程》例题源码_第3页
《大学C程序设计教程》例题源码_第4页
已阅读5页,还剩136页未读 继续免费阅读

下载本文档

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

文档简介

第1章C++语言简介例1-1第一个C++程序,在计算机屏幕上显示:HelloWorld!//Example1-1:屏幕上显示:HelloWorld!#include<iostream.h> 〃包含基本输入输出库文件intmain()〃主函数名intmain()cout«"HelloWorld!"«endl; 〃屏幕显示语句return0;return0;〃表示程序顺利结束)例1・2使用欧儿里德算法,编写--程序求解任意两个正整数的最大公因数。//Example1-2:计算两个正整数的最大公因数intmain()#include<iostream.h>〃包含基本输入输出库文件#include<iostream.h>〃包含基本输入输出库文件/Z说明三个整型变量p,q,rintp,q,r;//提示用户由键盘输入两个正整数cout«”Pleaseinputtwointegernumbers:"«endl;cin»p»q;//如果p<q,交换p和qif(p<q){r=p;p=q;q=r;/Z计算p除以q的余数rr=p%q;/Z只要r不等于0,重复进行下列计算while(r!=0)(p=q;q=r;r=p%q;}/Z输出结果cout«"Themaximumcommondivisoris"«q« «endl;return0;)例L3计算星球之间的万有引力。“Example1-3:计算星球之间的万有引力#include<iostream.h>doublegrav(doubleml,doublem2,doubledistance)(doubleg,G=6.67E-11;g=G*ml*m2/(distance*distance);returng;)intmain()(doubleGse,Gme;〃太阳质量1.987x1()3。千克,地球质量5.975x1()24千克,两者间距1.495x10”米doubleMsun=1.987E30,Mearth=5.975E24;Gse=grav(Msun,Mearth,1.495E11);cout«"Thegravitationbetweensunandearthis"«Gse«"N,"«endl;〃月亮质量7.348x1()22千克,地球质量5.975x1()24千克,两者间距3.844x1()5米doubleMmoon=7.348E22,Dme=3.844E5;Gme=grav(Mmoon,Mearth,Dme);cout«"Thegravitationbetweenmoonandearthis"«Gme«"N."«endl;return0;例1・4加法计算器程序。//Example1-4I加法计算器程序#include<iostream.h>intmain(){doublea,b,c;coutくぐPleaseinputtwonumbers:M;cin»a»b;c=a+b;cout«a«n+n«b«"=*'«c«endl;return0;)例1・5显示生日卡。该程序首先要求输入收信人和发信人的姓名,然后在屏幕上显示岀完整的生日卡来。//Example1-5:显示生日卡#include<iostream.h>intmain()(charname1[41],name2[41];cout«endl«nPleaseinputyourinend'sname:cin»namel;cout«endl«"Pleaseinputyourname:cin»name2;cout«endl«"===================================="«endl;cout«"Mydear"«namel«**,"«endl;cout«"Happybirthdaytoyou!"«endl;cout«” yours,"«endl;cout«” "«name2«endl;cout« —— - v<endl;return0;)例L6使用梯形法计算定积分厶,其中。=0,6=1,被积函数为(x),取积分区间等分数为1000o//Example1-6:用梯形法计算定积分#include<iostream.h>

#include<math.h>〃包含标准数学函数的#include<math.h>〃包含标准数学函数的math.h函数库intmain()doublea,b;/Z双精度类型变量:积分的下限和上限doubleh;/Z双精度类型变量:积分步长doublesum;/Z双精度类型变量:工作变量,最后为积分值intn;//整型变量:积分区间等分数inti;//整型变量:循环工作变量/Z根据题意确定积分的下限、上限和积分区间等分数a=0.0;b=1.0;n=1000;h=(b-a)/n;/Z计算小区间长度/Z为工作变量赋初值:先计算无需循环运算的部分sum=(sin(a)+sin(b))/2;//循环计算公式中的£和式for(i=l;i<n;i=i+l)sum=sum+sin(a+i*h);//完成计算,变量sum中存放积分结果sum=sum*h;/Z输出计算结果cout«"Theresultis"«sum«endl;return0;第2章控制结构例2-2编写一个程序,将百分制的学生成绩转换为优秀、良好、中等、及格和不及格的5级制成绩。标准为:优秀:100.90分;良好:80-89分;中等:70-79分;及格:60-69分;不及格:60分以下。//Example2-2:将百分制的分数转换为5级制分数#include<iostream.h>intmain()(intold_grade,new_grade;coutv<"Pleaseinputthescore:";cin»old_grade;switch(old_grade/10)(case10:case9:new_grade=5;break;case8:new_grade=4;break;case7:new_grade=3;break;case6:new_grade=2;break;default:new_grade=1;1coutvぐBeforetransformed,thescoreis,,«old_grade«endl;coutくぐAftertransformed,thescoreis,,«new_grade«endl;return0;例2.3计算e=1H 1 1■…d 1■…,当通项一<107时停止计算。1!2i鹿! 川//Example2-3I计算常数e的值#include<iostream.h>intmain()(doublee=1.0;doubleu=1.0;intn=1;while(u>=1.0e-7)(u=u/n;e-e+u;n=n+1;)cout«"e=n«e«n(n="«n«")"f«endl;return0;1例2-4使用do-while结构重新编写上题的程序。//Example2-4:计算常数e的值#include<iostream.h>intmain()(doublee=1.0;doubleu=1.0;intn=1;do{u=u/n;e=e+u;n=n+l;}while(u>=1.OE-7);cout«"e="«e«"(n="«n«")"«endl;return0;)例2-5求水仙花数。如果一个三位数的个位数、十位数和百位数的立方和等于该数自身,则称该数为水仙花数。编ー程序求出所有的水仙花数。//Example2-5:打印所有的水仙花数#includeく沁stream.h>intmain()(intn,i,j,k;for(n=100;n<=999;n=n+l){i=n/100; 〃取出n的百位数j=(n/10)%10;/Z取数n的十位数k=n%10; /Z取出n的个位数if(n==i*i*i+j*j*j+k*k*k)cout«n«H=M«i«',A3+M«j«,,A3+n«k«"A3H«endl;)return0;)例2-6猜幻数游戏。系统随机给出ー个数字(即幻数),游戏者去猜,如果猜对,打印成功提示,否则打印出错提示,并提示游戏者选择下ー步动作,最多可以猜5次。//Example2-6:猜幻数游戏#include<iostream.h>#include<stdlib.h>intmain()(intmagic;intguess;magic=rand();cout«"Guessthemagicnumber.Itisbetween0and32767.M«endl;for(inti=l;i<=5;i=i+l)(cin»guess;if(guess==magic)cout<v”***Right****<vendl;break;elseif(i==5)coutvv”TheH«i«utimeiswrong.Endofgame!M«endl;else(if(guess<magic)cout«MYouhavebeenwrongforH«i«"time(s).Pleasetryabiggerone."«endl;elsecout«MYouhavebeenwrongforM«i«Htime(s).Pleasetryasmallerone.M«endl;}}}return0;)实例编程 验证哥德巴赫猜想//Example:“验证”哥徳巴赫猜想#includeく沁stream.h>#defineM10001 //定义验证范围/Z函数CreatPrimeListO:生成素数表voidCreatPrimeList(intPrimeListJ])(inii,j;//将PrimeList的各元素设置为从〇开始的正整数for(i=0;i<M;i=i+l)PrimeList[i]=i;/Z分别从表中去掉已经确定的各素数的倍数(将其置为0)i=2;while(i<M/2)for(j=i+l;j<M;j=j+l)if(PrimeList|j]!=O&&PrimeList[j]%PrimeList[i]==O)PrimeList[j]=0;//确定下一个素数的位置i=i+1;while(PrimeList[i]==O)i=i+1;/Z函数NextPrimeNumber():求下ー个素数intNextPrimeNumber(intp,intPrimeList[])(p=p+l;while(PrimeList[p]==O)p=p+l;returnPrimeList[p];)/Z主函数:在从4到M的范围内验证哥德巴赫猜想intmain()(intPrimeList[M]; /Z说明存放素数表的数组intx,p; /Z变量X:偶数,p:素数//建立素数表CreatPrimeList(PrimeList);/Z对从4到M的所有偶数验证哥德巴赫猜想while(x<M)/Z检查偶数减去ー个素数后的剩余部分是否仍为素数p=PrimeList[2];while(p<=x/2&&PrimeList[x-p]==O)p=NextPrimeNumber(p,PrimeList);/Z输出检查结果if(p>x/2)/Z找到了一个不能分解为两个素数和的偶数cout«"Greatdiscovery:Goldbachiswrong!"«endl;else//PrimeList[x-p]#O,分解成功cout«"Theevennumber"«x«"="«p<<"+"«x-p«endl;/Z检查下ー个偶数x=x+2;)return0;)第3章基本数据类型例3-1利用迭代公式求平方根。设ズ=厶,则迭代公式为_(ム+。/ム)シ= 2迭代结束条件取相对误差X"+I"X"<£。X"+l//Example3-1:用迭代公式求平方根#include<iostream.h>#include<math.h>#defineEPS1.0e-10intmain()(doublex,y;cout«'*Pleaseinputthevalue:";cin»x;doublexO,xl;xl=1.0;if(x>0.0)(do(xO=x1;xl=(x0+x/x0)/2;}while(fabs((xO-xl)/x1)>=EPS);//fabs()函数为求绝对值的库函数y=xl;)elsey=x;if(y<0)cout«"NegativeValuehavenotsquareroot!"«endl;elsecout«"Thesquarerootof"«x«"is"«y«endl;return0;例3-2根据键盘输入的苜字符选择对应颜色(枚举类型的输入和输出)//Example3-2!选择颜色#include<iostream.h>inimain()(〃定义枚举类型颜色并同时声明一个该类型的变量enumColors)blue,brown,green,red,white,yellow}choose;charchi,ch2;cout«"Pleaseinputthefirsttwolettersofthecolorsyou'vechosen:H«endl;cin»chl»ch2;〃输入两个字符〃判断键盘输入字符所对应的枚举类型值switch(chl)|case'b’:if(ch2==,l,)choose=blue;elsechoose=brown;break;case'g':choose=green;break;case'r':choose=red;break;case'w':choose=white;break;casey:choose=yellow;break;default:cout«Mniegalinput!,,«endl;)〃输出枚举类型值switch(choose)(caseblue:cout«MThecoloryou'vechosenisblueH«endl;break;casebrown:cout«nThecoloryou'vechosenisbrownM«endl;break;casegreen:cout«nThecoloryou'vechosenisgreenM«endl;break;casered:cout«MThecoloryou'vechosenisredM«endl;break;casewhite:cout«MThecoloryou'vechoseniswhite"«endl;break;caseyellow:cout«nThecoloryou'vechosenisyellow,,«endl;)return0;)例3・3编写程序制作九九乘法表。//Example3-3:制作乘法表#include<iostream.h>intmain()(inti,j;for(i=l;i<10;i=i+l)|for(j=l;j<=i;j=j+l)cout«j«M*U«i«n=M«i*j«M\tn;cout«endl;}return0;)io例3-4计算l!+2!+3!+4!+......+10!.即、[!。r=l//Example3-4:求阶乘的和#include<iostream.h>intmain()intsum=0,u=1;for(inti=l;i<=10;i=i+l)u=u*i;sum=sum+u;)cout«nsum=H«sum«endl;return0;}例3・5求兀的近似值。//Example3-5:求兀的近似值#include<iostream.h>#include<math.h>intmain()(ints=1;doublen=1.0,u=1.0,pi=0.0;while(fabs(u)>=1e-4){pi=pi+u;n=n+2;s=-s; 〃符号位的生成u=s/n;)cout«"pi="«4*pi«endl;return0;}例3・6根据三边长求三角形面积。//Example3-6I求三角形面积#include<iostream.h>#include<math.h>intmain()(doublea,b,c,s,area;cout«”pleaseinputa,b,c=?”;cin»a»b»c;s=(a+b+c)/2;area=sqrt(s*(s-a)*(s-b)*(s-c));cout«"area="«area«endl;return0;)例3-7输入ー个四位无符号整数,反序输出这四位数的四个数字字符。//Example3-7:反序输出4位无符号整数的四个数字字符#include<iostream.h>intmain()(unsignedintn;charcl,c2,c3,c4;cout«MPleaseinputoneintegerbetween100()and9999:M«endl;cin»n;cout«"Beforeinversethenumberis:H«n«endl;cl=n%10+'0'; 〃分离个位数字c2=n/10%10+'0'; 〃分离十位数字c3=n/100%10+'0'; 〃分离百位数字c4=n/1000+'0'; 〃分离千位数字cout«',Afterinversethenumberis:H«cl«c2«c3«c4«endl;return0;)例3・8 编写ー个可以打印任何一年的日历的程序。要求:输入 某一年的年号 输出 该年每个月的日历//Example3-8:打印年历#include<iostream.h>#defineYES 1 //定义符号常数“是”#defineNO 0 //定义符号常数“否”/Z函数isleapO:判断某年是否闰年intisleap(intyear)(intleap=NO;if(year%4==0&&year%100!=0||year%400==0)leap=YES;returnleap;}/Z函数week_of_newyears__day():求元旦是星期几intweek_ofLnewyears_day(intyear)

intn=year-1900;n=n+(n-l)/4+1;n=n%7;returnn;}/Z主函数:打印年历intmain()intyear,month,day,weekday,len_o匚month,i;cout«°Pleaseinputyear:cin»year;/Z打印年历/Z打印年份/Z打印年份/Z求元旦是星期几/Z打印12个月的月历weekday=week_o匚newyears_day(year);for(month=1;month<=12;month=month+1)cout«endl«month«endl;cout«" "«endl;cout«nSUNMONTUEWEDTHUFRISET"«endl;cout«“ “«endl;fbr(i=O;i<weekday;i=i+1)/Zfbr(i=O;i<weekday;i=i+1)/Z找当月1丨I的打印位置cout«" ";if(month==4||month==6||month==9||month==l1)len_ofLmonth=30;elseif(month==2)(if(isleap(year))len_of_month=29;elselen_of_month=28;)elselen_of_month=31;for(day=1;day<=len_of_month;day=day+1)/Z打印当月日期{if(day>9)cout«day«n”;elsecout«day«”weekday=weekday+1;if(weekday==7) /Z打满一星期应换行{weekday=0;cout«endl;}}cout«endl; /Z打完一月应换行)return0;}实例编程 模拟仿真在码头酒馆和游船之间搭了一条长20米,宽4米的跳板,醉酒的船员和游客回艇时必须通过这个跳板。通过跳板时,有三种可能的结果:1)向前走,回到游船上休息,不再出来;2)转身回到酒馆,重新开始喝酒,不再出来;3)左右乱晃,落入水中淹死。如果醉酒者每次走・步,ー步走1米。而且他们向前走的概率是。.7,向左走、向右走和向后走的概率各为0」。现在假设开始时他们都是站在酒馆的门ロ,请编写程序模拟出若干个醉酒者的最终行为结果。//Example模拟仿真程序#include<iostream.h>#include<math.h>#include<stdlib.h>constintSHIP”constintBAR=2;constintWATER=3;〃ー个醉酒者行为的模拟仿真intdrunkard(void){intx=-10; 〃记录醉酒者的x坐标,开始时在酒馆门口inty=0; 〃记录醉酒者的y坐标,开始时在跳板的中央intstep=O; 〃记录醉酒者ー共走了多少步while(abs(x)<=10&&abs(y)<=2)(switch(rand()%10){case0:〃向左走y=y-i;break;〃向右走y=y+i;break;〃向后走x=x-l;break;〃向前走x=x+l;)step=step+1;)if(x<-10)(cout«"Aftern«step«Hsteps,themanreturnedtothebaranddrunkagainM«endl;returnBAR;)else(if(x>10)cout«"After',«step«"steps,themanreturnedtotheshipn«endl;returnSHIP;else

cout«"AfterM«step«Msteps,themandroppedintothewater,'«endl;returnWATER;))}〃反映若干个醉酒者最终行为的模拟仿真的主函数intmain()intdrunkardnumber;〃醉酒者总数intshipnumber=O;〃到达船上的人数ntbamumber=O;〃返冋酒馆的人数intwatemumber=O;〃掉进水中的人数cout«"Pleaseinputthenumberofdrunkard"«endl;cin»drunkardnumber;fdr(inti=0;i<drunkardnumber;i=i+l)switch(drunkard())caseSHIP:shipnumber=shipnumber+1;break;caseBAR:barnumber=barnumber+1;break;caseWATER:waternumber=waternumber+1;break;]cout<<"******************************"vVendl‘cout«HOfallthe,,«drunkardnumber«Mdrunkards:M«endl;cout«shipnumber«Hreturnedtotheship"«endl;coutvvbamumbervぐ’wenttothebaranddrunkagain"«endl;cout«waternumber«"droppedintothewater"«endl;return0;第4章数组与结构体例4-1给ー维数组x输入10个整数,找出x数组中的最大数。//Example4-1:求数组中的最大元素#include<iostream.h>intmain()(intarray[7];cout«MPleaseinputanarraywithsevenelements:H«endl;for(inti=0;i<7;i++)cin»array[i];intbig=array[0];for(intj=0;j<7;j=j+l)if(array[j]>big)big=array[j];cout«nmax=M«big«endl;return0;)例4-2字符串的输入与输出。//Example4-2:字符串的输入与输出#include<iostream.h>intmain(){charname1[20],name2[20];cout«"Pleaseinputanamewithblank(within19characters):M«endl;cin.get(namel,20);cout«"PleaseinputthenameagainM«endl;cin»name2;cout«uUsingfunctionget,thenamestoringinthevariableis:"«namel«endl;cout«uUsingoperater«,thenamestoringinthevariableis:,'«name2«endl;return0;)例4-3编写ー个用来计算字符串长度的函数mystrlen(),并用主函数验证。//Example4-3:求字符串的长度#include<iostream.h>〃计算字符串的长度的函数intmystrlen(charstring[J)intlen=0;whileCstringdenli^O1)len=len+l;returnlen;}〃测试计算字符串长度的主函数intmain()(charstring[100J;intlen=0;coutvぐ'Pleaseinputastring(within99characters):"«endl;cin»string;cout«"Thelengthofthestringis:"«mystrlen(string)«endl;return0;}例4・4编写ー个程序,实现矩阵相乘运算。//Example4-4I计算两个矩阵的乘积#include<iostream.h>intmain()(constintL=4;constintM=5;constintN=3;doublea[L*M]=(1.0,3.0,-2.0,0.0,4.0,-2.0,-1.0,5.0,-7.0,2.0,0.0,8.0,4,0,1.0,-5.0,3.0,-3.0,2.0,-4.0,1.0};doubleb[M*N]=(4.0,5.0,-1.0,2.0,-2.0,6.0,7.0,8.0,1.0,0.0,3.0,-5.0,9.0,8.0,-6.0);doublec[L*N];inti,j,k;for(i=0;i<L;i=i+l)for(j=0;j<N;j=j+l){c[i*N+jJ=0;for(k=0;k<M;k=k+l)c[i*N+j]=c[i*N+j]+a[i*M+k]*b[k*N+j];)cout«”Theresultisc=M«endl;for(i=0;i<L;i=i+l)|for(intj=0;j<N;j=j+l)cout«c[i*N+j]«HH;cout«endl;}return0;)例4・5编写ー个用于对整型数组进行排序的程序,排序方法使用简单的交换排序法。//Example4-5:交换排序#include<iostream.h>intmain(){constintCOUNT=16;intlist[COUNT]=|503,87,512,61,908,170,897,275,653,426,154,509,612,677,765,703);for(inti=0;i<COUNT;i=i+l)for(intj=COUNT-l;j>i;j=j-1)if(listU-l]>listU])(inttmp=list[j-l];list[j-l]=list[j];listfj]=tmp;)cout«”Theresultis:"«endl;for(intk=0;k<16;k++)cout«list[k]«い;cout«endl;return0;)例4-6编写ー个字符串处理程序,将一个字符串中的所有小写字母转换为相应的大写字母。//Example4-6:将字符串中所有的小写字母转换为大写字母#include<iostream.h>intmain()(charstr[]="Thisisasample";cout«"Theoriginalstringis:"«str«endl;inti=0;while(str[i]!=0)(if(strli]>='a'&&str[i]<='z,)strfi]=str[i]-'a'+'A';i=i+1;1cout«MAftertransform:"«str«endl;return0;)例4-7使用数组编写ー个统计学生课程平均分的程序;输入6个学生的学号和3门课程的成绩(整型),统计每个学生3门课程的平均分,最后输出统计结果。输出格式:学号成绩1成绩2成绩3平均分//Example4-7:统计学生课程的平均分#include<iostream.h>#definePERSON 6#defineCOURSE 3intmain()intstudent[PERSON][COURSE+2];inti,j;cout«nPleaseinputdataofstudent:M«endl;for(i=0;i<PERSON;i=i+l)(cin»student[i][O];student[i][COURSE+l]=0;for(j=1;j<=COURSE;j=j+1)(cin»student[i][j];student[i][COURSE+l]=student[i][COURSE+l]4-student|i][j];}student[i][COURSE+l]=student[i][COURSE+l]/COURSE;}coutvぐ学号高数英语体育平均分”vvendl;cout«M "vvendl;for(i=0;i<PERSON;i=i+1)(for(j=0;j<=COURSE+l;j=j+l)cout«student[i][j]«,,\tM;cout«endl;)return0;)例4・8使用结构体重新编写上题的程序。//Example4-8:统计学生课程的平均分#include<iostream.h>#definePERSON 6#defineCOURSE 3structStudentType(charid[10]; 〃学号intscoreLCOURSEJ; 〃课程成绩intGPA; 〃平均分};intmain(){StudentTypexjtuStudent[PERSON];inti,j;cout«',Pleaseinputdataofstudent:H«endi;fbr(i=O;i<PERSON;i=i+l)cin»xjtuStudent[i].id;xjtuStudent[i].GPA=O;for(j=0;j<COURSE;j=j+l){cin»xjtuStudent[i].score[j];jtuStudent[i].GPA=xjtuStudent[i].GPA+xjtuStudent[i].score|j];}xjtuStudent[i].GPA=xjtuStudentfi].GPA/COURSE;cout«”学号高数英语体育平均分”<<endl;cout«n H«endl;for(i=0;i<PERSON;i=i+l)(cout«xjtuStudent[i].id«n\t";for(j=0;j<COURSE;j=j+l)cout«xjtuStudent[i].score|j]«,'\t,';cout«xjtuStudent[i].GPA«endl;}return0;第5章表达式例5・1字符串连接。//Example5-1:连接两个字符串#include<iostream.h>#include<string.h>intmain()(chardestination[81]=,,abcdefghijklmnopqrstuvwxyz,';charsource[]=,'ABCDEFGHIJKLMNOPQRSTUVWXYZ,';inti=strlen(destination);intj=0;while(source[j]!=0)destination[i++]=source|j++];destination[i]=0;cout«nTheresultis:n«destination«endl;return0;)例5-2名字空间的使用。//Example5-2:名字空间的使用#include<iostream>namespaceuniversity(intgrade=4;)namespacehighschool{intgrade=3;1intmain()std::cout«"Theuniversity*sgradeis:"«university::grade«std::endl;std::cout«MThehighschoofsgradeis:M«highschool::grade«std::endl;return0;例5-3编写ー个求绝对值的函数。//Example5-3:求双精度类型量的绝对值doublemydabs(doublex)(returnx>0?x:-x;)例5-4取一个整型变量的最低4位。//Example5-4:宏tranl6():取整型量的最低4位#definetran16(x) ((x)&0x0f)例5・5求一元二次方程ax2+bx+c=0的根,其中系数a,b,c为实数,由键盘输入。//Example5-5I解一元二次方程#include<iostream.h>#include<math.h>intmain()(doublea,b,c,delta,p,q:cout«"pleaseintputa,b,c=?cin»a»b»c;delta=b*b-4*a*c;p=-b/(2*a);q=sqrt(fabs(delta))/(2*a);if(delta>=0)cout«endl«"x1="«p+q«endl«"x2="«p-q«endl;else(cout«endl«"x1="«p«"+jn«q;cout«endl«"x2=*'«p«M-j"«q«endl;)return0;)例5-6对于任意给定的ー个正整数n,统计其阶乘n!的末尾中〇的个数。//Example5-6:统计阶乘n!的末尾中。的个数#include<iostream.h>intmain()(intn;intm;intsum=O;cout«°Pleastinputapositivenumber:H;cin»n;for(inti=5;i<=n;i=i+5)〃只有5的倍数オ含5的因子(m=i;for(intk=0;m%5==0;k=k+l)m=m/5;sum=sum+k;)cout«"ThenumberofzeroinM«n«n!is:H«sum«endl;return0;)例5・フ计算50!//Example5-7:利用数组计算阶乘#include<iostream.h>intmain()(constintMAXSIZE=100;intarray[MAXSIZE];intn=50;intsum,sc;for(inti=0;i<MAXSIZE;i++)array[i]=0;array[0]=l;fbr(i=2;i<=n;i++){sc=0;for(intj=0;j<MAXSIZE;j++){sum=array[j]*i+sc; 〃上一次进位值和当前计算结果求和sc=sum/10; //存放进位数值array[j]=sum%10; 〃将余数存入数组})for(i=MAXSIZE-1;i>=0;i—)cout«array[i];cout«endl;return0;例5-8编写ー个用于对整型数组进行排序的函数,排序方法使用希尔排序法。//Example5-8I 希尔排序#include<iostream.h>voidshell_sort(intlist[],intcount)(intexchange,i,tmp,gap=count;while(g叩>1)〃每循环一次,步长减为原来的一半(gap=gap/2;do//循环直到当前子序列完全有序(exchange=0;fbr(i=O;i<count-gap;i=i+l){if(list[i]>list[i+gap])(tmp=list[i];Iist[i]=list[i+gap];list[i+gap]=tmp;exchange=1;))}while(exchange!=O);)}//测试希尔排序的主程序intmain()(inti,list[16]=(59,20,17,13,28,14,23,83,36,98,11,70,65,41,42,15};shell_sort(list,16);cout«MTheresultis:M«endl;for(i=0;i<16;i++)cout«list[i]«ncout«endl;

return0;)例5-9找出2~10000之内的所有完全数。所谓完全数,即其各因子之和正好等于本身的数。如6=1+2+3,28=1+2+4+7+14,所以6,28都是完全数。//Example5-9I寻找完全数#include<iostream.h>intmain()(intk;intn=2;while(n<=10000)(k=0;fbr(intm=l;m<=n/2;m++)if(n%m==0)k=k4-m;if(k==n)cout«Hfindone:H«k«endl;n++;)return0;实例实例编程Josephus问题Josephus问题是说,一群小孩围坐成一圈,现在任意取ー个数n»从当前编号为ー的孩子开始数起,依次数到n(因为围成了一圈,所以可以不停的数下去),这时被数到n的孩子离开,然后从圈子缩小一点。如此重复进行,小孩数不断减少,圈子也不断缩小。最后所请找出这个胜利者。剩的那个小孩就是胜利者。请找出这个胜利者。#include<iostream.h>intmain()constintTotal=7;〃小孩总数intChooseNum;〃用户随机选取的数intboy[Total];〃表示小孩的数组constintTotal=7;〃小孩总数intChooseNum;〃用户随机选取的数intboy[Total];〃表示小孩的数组for(inti=0;i<Total;i++)boy[i]=i+l;〃给小孩编号cout«MPleaseinputthenumberwhichistobeeliminated:n;cin»ChooseNurn; 〃用户随机输入ー个剔除的数cout«nBeforeeliminating,theboysare:/r

温馨提示

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

评论

0/150

提交评论