文档详情

《大学C++程序设计教程》例题源码

奇异
实名认证
店铺
DOCX
152.97KB
约137页
文档ID:168055792
《大学C++程序设计教程》例题源码_第1页
1/137

第1章C++语言简介例1-1第一个C++程序,在计算机屏幕上显示:Hello World!// Example 1-1:屏幕上显示:Hello World!#include 〃包含基本输入输出库文件int main() 〃主函数名(cout« "Hello World!" « endl; 〃屏幕显示语句return 0: 〃表示程序顺利结束)例1-2使用欧几里徳算法,编写ー程序求解任意两个正整数的最大公因数〃 Example 1-2:计算两个正整数的最大公因数#include 〃包含基本输入输出库文件int main()(/Z说明三个整型变量p, q, rint p, q, r;//提示用户由键盘输入两个正整数cout« "Please input two integer numbers:" « endl;cin » p » q;//如果pvq,交换p和qif(pvq)|r = p;p = q;/Z计算p除以q的余数rr = p%q;/Z只要r不等于0,重复进行下列计算while(r != 0)|p = q;q = r;r = p%q;}/Z输出结果cout« ”The maximum common divisor is " « q « « endl;return 0;I例1・3计算星球之间的万有引力。

Example 1・3:计算星球之间的万有引力#include double grav(double ml, double m2, double distance)(double g, G = 6.67E-11;g = G*m 1 *m2/(distance*distance);return g;)int main()(double Gse, Gme;〃太阳质量1.987x1()3千克,地球质量5.975x1()24千克,两者间距1.495米double Msun = 1.987E30, Mearth = 5.975E24;Gse = grav(Msun, Mearth, 1.495E11);cout« "The gravitation between sun and earth is "« Gse «" N." « endl;〃月亮质量7.348x1()22千克,地球质量5.975x1()24千克,两者间距3.844xl(f米double Mmoon = 7.348E22, Dme = 3.844E5;Gme=grav(Mmoon, Mearth, Dme);cout « "The gravitation between moon and earth is "« Gme «" N." « endl; return 0;例レ4加法计算器程序。

// Example 1-41加法计算器程序#include int main(){double a, b, c;cout«HPlease input two numbers: M;cin»a»b;c = a+b;cout« a « n + “ « b w " = " « c« endl;return 0;}例レ5显示生日卡该程序首先要求输入收信人和发信人的姓名,然后在屏幕上显示出完 整的生日卡來// Example 1-5:显示生日卡#include int main(){char namel [41], name2[41];cout« endl « "Please input your friend^ name: **;cin » name 1;cout« endl « "Please input your name:";cin » name2;cout« endl « "==============" « endl;cout« "My dear" « namel « ", " « endl;cout« " Happy birthday to you!" « endl;cout« " yours, " « endl;cout« " " « name2 « endl;cout« “============== ===" « endl;return 0;}ph例1-6使用梯形法计算定积分]/(x)dx ,其中。

0, b=l,被积函数为si”(x),取积分区间等分数为1000// Example 1-6:用梯形法计算定积分 #include #include 〃包含标准数学函数的math.h函数库int main()(double a, b; /Z双精度类型变量:积分的下限和上限double h; /Z双精度类型变量:积分步长double sum; /Z双精度类型变量:工作变量,最后为积分值intn; //整型变量:积分区间等分数inti; //整型变量:循环工作变量/Z根据题意确定积分的下限、上限和积分区间等分数a = 0.0;b= 1.0;n= 1000;h = (b-a)/n; /Z计算小区间长度/Z为工作变量赋初值:先计算无需循环运算的部分sum = (sin (a)+ sin (b))/2;//循环计算公式中的E和式fbr(i=l;i

标准为:优秀:100-90分;良好:80-89分;中等:70-79分;及格:60-69分;不及格:60分以下// Example 2-2:将百分制的分数转换为5级制分数#include int main(){int old grade, new grade;coutvv”Please input the score:cin »old_grade;switch (old_grade/10)(case 10:case 9:newgrade = 5;break;case 8:newgrade = 4;break;case 7:newgrade = 3;break;case 6:newgrade = 2;break;default:newgrade = 1;)coutvv“Befbre transformed, the score is ,,«old_grade«endl;cout«”After transformed, the score is ,,«new_grade«endl;return 0;例2-3计算e = l+丄+丄+ ... +丄+ ...,当通项丄くIO々时停止计算。

1! 2! n\ n\// Example 2-3:计算常数e的值#include int main(){double e = 1.0;double u = 1.0;int n = 1;while(u >= 1 .Oe-7){u = u/n;e = e+u;n = n+1;}cout« ”e = n « e « n ( n = '( « n « n )H « endl;return 0;)例2・4使用do・while结构重新编写上题的程序// Example 2-41计算常数e的值#include int main()(double e = 1.0;double u = 1.0;int n= 1;do(u = u/n;e = e+u;n = n+1;}while(u>=1.0E-7);cout« Me = M « e « M ( n = " « n « H )M « endl;return 0;例2・5求水仙花数如果一个三位数的个位数、十位数和百位数的立方和等于该数自身, 则称该数为水仙花数编ー程序求出所有的水仙花数// Example 2-5:打印所有的水仙花数#include int main()(int n, i,j,k;for(n=100; n<=999; n=n+l){i = n/100; 〃取出n的百位数j = (n/10)%10; /Z取数n的十位数k = n%10; 〃取出n的个位数if(n=i*i*i+j*j*j+k*k*k)cout «n«M = M«i«"A3 + M<

系统随机给出ー个数字(即幻数),游戏者去猜,如果猜对,打印成功提示,否则打印出错提示,并提示游戏者选择下ー步动作,最多可以猜5次// Example 2-6:猜幻数游戏#include #include int main()(int magic;int guess;magic=rand();cout«"Guess the magic number. It is between 0 and 32767."vvendl;fbr(int i=l; i<=5; i=i+l)(cin»guess;i 出 guess-magic)cout«M* * *Right* * *M«endl; break;elsecout«HThe n«i«M time is wrong. End of game!H«endl; else (ifi(guess#define M 10001 //定义验证范围〃函数CreatPrimeList():生成素数表void CreatPrimeList(int PrimeList[]){inti,j;//将PrimeList的各元素设置为从0开始的正整数for(i=0; ix/2) /Z找到了一个不能分解为两个素数和的偶数cout«nGreat discovery: Goldbach is wrong!M«endl;else // PrimeList[x・p并〇,分解成功cout«*'The even number M«x«'-H«p«M + M«x-p«endl;/Z检查下ー个偶数x = x+2;}return 0;第3章 基本数据类型例3-1利用迭代公式求平方根。

设为=后,则迭代公式为_ (xn +a/xn)Xn+1 . 2迭代结束条件取相对误差ム+1 ー—< £ . £+1// Example 3-1 :用迭代公式求平方根#include #include #define EPS 1.0e-10int main(){double x, y;cout« MPlease input the value :";cin » x;double xO, x 1;xl = 1.0;if(x>0.0)(doxl = (x0+x/x0)/2;}while(fabs((xO-x 1 )/x 1 )>=EPS); 〃ロbs()函数为求绝对值的库函数 y=xl;}elsey=x;ifly int main()〃定义枚举类型颜色并同时声明・个该类型的变量enum Colors{ blue, brown, green, red, white, yellow} choose;char chi, ch2;cout«HPlease input the first two letters of the colors you've chosen:**«endl;cin»ch l»ch2; 〃输入两个字符〃判断键盘输入字符所对应的枚举类型值switch(chl)|case *b,:ifi(ch2=,r)choose=blue;elsechoose=brown;break;case *g*:choose=green;break;case Y:choose=red;break;case 'w’:choose=white;break;case y:choose=yellow;break;default:cout«nIllegal input!"«endl;}〃输出枚举类型值switch(choose)(case blue:cout«HThe color you've chosen is blueM«endl;break;case brown:cout«HThe color you've chosen is brownM«endl; break;case green:cout«HThe color you've chosen is greenn«endl;break;case red:cout«HThe color you've chosen is redH«endl;break;case white:cout«nThe color you've chosen is whiteH«endl;break;case yellow:cout«HThe color you've chosen is yellowH«endi;)return 0;)例3-3编写程序制作九九乘法表。

// Example 3-3:制作乘法表#include int main()(int ij;fbr(i=l; i<10; i=i+l)(for(j=l;j<=i;j=j+l)cout «j «M*"« i ««=»»«i*j «M\tM; cout« endl;}return 0;}io例 3-4 计算 l!+2! +3! +4! +......+10!1即Xれi=\// Example 3-4:求阶乘的和#include int main()int sum = 0, u = 1;fbr(int i=l; i<=10; i=i+l)u = u*i;sum = sum+u;}cout«Hsum = M«sum«endl;return 0;)例3・5求兀的近似值// Example 3-5:求n的近似值#include #include int main(){int s = 1;double n = 1.0, u = 1.0, pi = 0.0; while( fabs(u)>= 1 e-4) (pi = pi+u;n = n+2;s = -s; 〃符号位的生成u = s/n;)cout « npi = " « 4*pi « endl; return 0;)例3-6根据三边长求三角形面积。

// Example 3-6!求三角形面积#include #include int main(){double a, b, c, s, area;cout « "please input a, b, c =?**;cin » a » b » c;s = (a+b+c)/2;area = sqrt(s*(s-a)*(s-b)*(s-c));cout« "area = " « area « endl;return 0;例3-7输入ー个四位无符号整数,反序输出这四位数的四个数字字符//Example 3-7:反序输出4位无符号整数的四个数字字符 #include int main()unsigned int n;char cl,c2,c3,c4;cout«HPlease input one integer between 1000 and 9999: M«endl;cin»n;cout«MBefore inverse the number is: M« n «endl;cl=n%10+'0’;c2=n/10%10+,0,;〃分离十位数字c3=n/100%10+'0’;〃分离百位数字c4=n/l 000+0;〃分离千位数字cout«MAfter inverse the number is: ,,<

要求:输入 某一年的年号 输出 该年每个月的日历//Example 3-8:打印年历#include #defineYES 1 //定义符号常数“是“#define N0 0 //定义符号常数”否“/Z函数isleap():判断某年是否闰年int isleap(int year)(int leap = NO;ifi(year%4==0 && year%100!=0 || year%400=0) le 叩=YES;return leap;)/Z函数week_of^newyears_day():求元旦是星期几 int week_of_newyears_day(int year)〃分离个位数字int n = year-1900;n = n+(n-l )/4+1;n = n%7;return n;)/Z主函数:打印年历int main(){int year, month, day, weekday, len_of_month, i;cout« MPlease input year: M;cin »year;/Z打印年历cout« endl « year « endl; /Z 打印年份weekday = week_of_newyears_day(year); /Z 求元旦是星期几 fbr(month=l; month<= 12;month=month+1) 〃打印 12 个月的月历 {cout« endl « month « endl;cout« ” " « endl;cout«HSUN MON TUE WED THU FRI SETH«endl;cout« ” " « endl;for(i=0;i9)cout« day « ” ”;else cout« day « ” weekday = weekday+1;if(weekday=7) /Z打满一星期应换行( weekday = 0; cout« endl; } cout« endl; /Z打完一月应换行) return 0;实例编程 模拟仿真在码头酒馆和游船之间搭了一条长20米,宽4米的跳板,醉酒的船员和游客回艇时必 须通过这个跳板。

通过跳板时,有三种可能的结果:1)向前走,回到游船上休息,不再出来;2)转身回到酒馆,重新开始喝酒,不再出来:3)左右乱晃,落入水中淹死如果醉酒者每次走ー步,ー步走1米而且他们向前走的概率是0.7,向左走、向右走 和向后走的概率各为01现在假设开始时他们都是站在酒馆的门ロ,请编写程序模拟出若 干个醉酒者的最终行为结果// Example模拟仿真程序#include #include #include const int SHIP=1;const int BAR=2;const int WATER=3;〃ー个醉酒者行为的模拟仿真int drunkard(void)int x=-10; 〃记录醉酒者的x坐标,开始时在酒馆门口inty=0; 〃记录醉酒者的y坐标,开始时在跳板的中央int step=O; 〃记录醉酒者ー共走了多少步while(abs(x)<= 10&&abs(y)<=2)(switch(rand()% 10){case 0: 〃向左走y=y-i;break;case 1: 〃向右走y=y+l;break;case 2: 〃向后走x=x-l;break;case 3: 〃向前走case 4:case 5:case 6:case 7:case 8:case 9:x=x+l;)step= step +1;)if(x<-10){cout«nAfter H«step«n steps, the man returned to the bar and drunk againH«endl; return BAR;)else{if(x>10)cout«nAfter ,,«step«M steps, the man returned to the shipn«endl; return SHIP;elsecout«HAfter "«step«n steps, the man dropped into the water**«endl; return WATER;)}〃反映若干个醉酒者最终行为的模拟仿真的主函数int main()int drunkardnumber;〃醉酒者总数int shipnumber=O;〃到达船上的人数nt bamumber=O;〃返回酒馆的人数int watemumber=O;〃掉进水中的人数cout«MPlease input the number of drunkardH«endl; cin»drunkardnumber;fbr(int i=0; i

// Example 4-1:求数组中的最大元素#include int main()(int array[7];cout«nPlease input an array with seven elements: M«endl;fbr(int i=0; i<7; i++)cin»array[i];int big = array [0];for(intj=0;j<7;j=j+l)if(array|j]>big)big = array[j];cout«,,max=,,«big«endl;return 0;)例4・2字符串的输入与输出// Example 4-2:字符串的输入与输出#include int main()(char namel [20], name2[20];cout«MPlease input a name with blank(within 19 characters): "«endl;cin.get(namel, 20);cout«HPlease input the name again"«endl;cin»name2;cout«HUsing function get, the name storing in the variable is: M«namel«endl; cout«HUsing operater «, the name storing in the variable is: M«name2«endl; return 0;}例4・3编写ー个用来计算字符串长度的函数mystrlen(),并用主函数验证。

//Example4-3:求字符串的长度#include 〃计算字符串的长度的函数int mystrlen(char string[])int len = 0;while(string[len] !=*\0*)len = len+l;return len;)〃测试计算字符串长度的主函数int main()(char string[100];int len = 0;cout«nPlease input a string (within 99 characters): M«endl;cin»string;cout«MThe length of the string is: H«mystrlen(string)«endl; return 0;)例4-4编写一个程序,实现矩阵相乘运算// Example 4-4:计算两个矩阵的乘积#include int main(){const int L=4;const int M=5;const int N=3;double a[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};double b[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};double c[L*N];int i,j,k;fbr(i=O; i=*a* && str[i]<=*z*) str[i] = str[i]-*a*+*A*;i = i+l;}cout«**After transform: **«str«endl;return 0;)例4-7使用数组编写ー个统计学生课程平均分的程序:输入6个学生的学号和3门课程的成绩(整型),统计每个学生3门课程的平均分,最 后输出统计结果。

输出格式:学号 成绩1成绩2 成绩3 平均分//Example 4-7:统计学生课程的平均分#include #define PERSON 6#define COURSE 3int main() {int student[PERSON][COURSE+2]; ■nt i,j;cout«HPlease input data of student :M«endl;fbr(i=0; i< PERSON; i=i+l){cin»student[i][O];student[i][COURSE+l]=0;fbr0=l;j<= COURSE; H+l) {cin»student[i][j];student[i][COURSE+l]=student[i][COURSE+l]+student[i][j];}student[i][COURSE4-l ]=student[i][COURSE+1 ]/ COURSE;)coutw”学号 高数 英语 体育 平均分" wendl;cout«n H«endl;fbr(i=O; i< PERSON; i=i+l) {fbr(j=O; j<= COURSE+1; j=j+l) cout«student[i][j ]«H\tM;cout«endl;}return 0;例4・8使用结构体重新编写上题的程序。

//Example 4-8:统计学生课程的平均分#include #define PERSON 6#define COURSE 3struct StudentType(charid[10]; 〃学号int score[COURSE]; 〃课程成绩int GPA; 〃平均分);int main()StudentType xjtuStudent[PERSON];int i,j;cout«nPlease input data of student :*'«endl;for(i=0; i< PERSON; i=i+l)cin» xjtuStudent[i].id;xjtuStudent[i].GPA=O;fbr(j=O; j< COURSE; j=j+l) {cin» xjtuStudent[i]. scorefj];jtuStudent[i]. GPA = xjtuStudent[i]. GPA + xjtuStudent[i]. score]]; )xjtuStudent[i]. GPA = xjtuStudent[i]. GPA / COURSE;}coutw”学号 高数 英语 体育 平均分“ vvendl;cout«M M«endl;fbr(i=O; i< PERSON; i=i+l) (cout«xjtuStudent[i].id«,,\t,';fbr(j=O;j< COURSE; j=j+l)cout« xjtuStudent[i].score[j]vv”\t”;cout« xjtuStudent[i].GPA«endI;return 0;第5章表达式例5・1字符串连接。

// Example 5-1 :连接两个字符串#include #include int main(){char destination[81] = nabcdefghijklmnopqrstuvwxyz*';char source[] = "ABCDEFGH1JKLMN0PQRSTUVWXYZ”;int i = strlen(destination);intj = O;while(source[j]!=0)destination[i++] = source[卄];destination[i] = 0;cout«nThe result is: n«destination«endl;return 0;)例5・2名字空间的使用// Example 5-2:名字空间的使用#include namespace university(int grade=4;)namespace highschool{int grade=3;}int main()(std::cout«HThe university*s grade is: n«university::grade «std::endl;std::cout«HThe highschoofs grade is: **«highschool::grade «std::endl; return 0;例5・3编写ー个求绝对值的函数。

//Example 5-3:求双精度类型量的绝对值double mydabs(double x){return x>0?x:-x;)例5・4取一个整型变量的最低4位// Example 5-4:宏tranl6():取整型量的最低4位#define tran 16(x) ((x)&0x0f)例5・5求一元二次方程ax、bx+c=0的根,其中系数a,b,c为实数,由键盘输入//Example 5-5:解一元二次方程#include #include int main(){double a, b, c, delta, p, q;cout« ”please intput a, b, c = ?cin » a » b » c;delta = b*b-4*a*c;p = -b/(2*a);q = sqrt(fabs(delta))/(2*a);iRdelta >= 0)cout« endl « "xl = " « p+q « endl « "x2 = " « p-q « endl;else(cout « endl « Mx 1 = " « p « " + j" « q;cout« endl « "x2 = " « p « " " j" « q «endl;return 0;}例5・6对于任意给定的ー个正整数n,统计其阶乘n!的末尾中〇的个数。

// Example 5-6:统计阶乘n!的末尾中〇的个数#include int main(){int n;int m;int sum=O;cout«nPleast input a positive number: u;cin»n;fbr(int i=5; i<=n; i=i+5) 〃只有5的倍数オ含5的因子 {m=i;fbr(int k=0; m%5==0; k=k+l)m=m/5;sum=sum+k;}cout«HThe number of zero in M«n«H! is: M«sum«endl;return 0;}例5・7计算50!// Example 5-7:利用数组计算阶乘#include int main()(const int MAXSIZE=100;int array[MAXSIZE];int n=50;int sum, sc;fbr(int i=0; i=0; i-) cout«array[i];cout«endl;return 0;例5-8编写一个用于对整型数组进行排序的函数,排序方法使用希尔排序法。

// Example 5-8I希尔排序#include void shell_sort(int list[], int count)(int exchange, i, tmp, gap = count;while(gap>l) 〃每循环一次,步长减为原来的一半{gap = gap/2;do //循环直到当前子序列完全有序(exchange = 0;fbr(i=O; ilist[i+gap])(tmp = list[i];list[i] = list[i+gap];list[i+gap] = tmp;exchange = 1;)}}while(exchange!=O);))〃测试希尔排序的主程序int main(){int i, list[16]={59, 20, 17, 13, 28, 14, 23, 83, 36, 98, 11, 70, 65,41, 42, 15};shell_sort(list,16);cout«HThe result is :M«endl;fbr(i=O; i<16; i++)cout«list[i]« " n;cout«endl;retum 0;)例5-9找出2〜10000之内的所有完全数。

所谓完全数,即其各因子之和正好等于本身的数 如 6=1+2+3, 28=1+2+4+7+14i所以 6, 28 都是完全数// Example 5-9:寻找完全数#include int main()int k;int n=2;while(n<= 10000){k=0;fbr(int m=l; m<=n/2; m-H-)iRn%m==0)k=k+m;ifi[k==n) cout«*'find one: M«k«endl;n++;)return 0;实例编程 Josephus问题Josephus问题是说,一群小孩围坐成一圈,现在任意取ー个数n,从当前编号为ー的孩 子开始数起,依次数到n (因为围成了一圈,所以可以不停的数下去),这时被数到n的孩 子离开,然后从圈子缩小一点如此重复进行,小孩数不断减少,圈子也不断缩小最后所请找出这个胜利者剩的那个小孩就是胜利者include int main()const int Total=7;〃小孩总数int ChooseNum;〃用户随机选取的数int boy[Total];〃表示小孩的数组for(int i=0; i

表示从第一个孩子开始数数while(true)|〃在圈中开始剔除fbr(int j=0; jl){result *= n;n-;)return result;)例6・2阶乘函数的调用。

Example 6・2:测试阶乘计算函数的主程序#include int main()(int n;c。

下载提示
相关文档
正为您匹配相似的精品文档