实验五
(1)已有一按从小到大次序排序好的数组,现输入一数,要求用折半查找法找出该数在数组中的位置。
实验数据:
数组值为:10,12,14,16,18,20,22,24,26,28 输入数: 16
(2)编写程序,实现str=str1+str2的操作,此处运算符“+”表示将两个字符串str1、str2连接成一个字符串str。用键盘将两个字符串输入字符数组str1与str2中,连接后的字符串存放在字符数组str中,并输出连接后的字符串str。
1)用C++提供的字符串处理函数完成上述要求。
2)不用C++提供的字符串处理函数完成上述要求。 实验数据:abcde fghij
(3)设计一个程序,按习题4.12的要求打印杨辉三角形。
(4)在表4.4中求每个学生的平均成绩及每门课的最高分与最低分,对学生成绩表用擂台法按平均成绩降序排序后输出。
表4.4 学生成绩情况表
学 号 1001 1002 1003 1004 1005 最高分 最低分 数 学 90 70 65 85 80 语 文 80 75 70 50 90 外 语 85 80 75 60 70 平均成绩
4.解答参考
(1)分析:对已排好序的数,折半查找法总是将要找的数与中间的元素比较,若大于它,则到后半部分去找,否则到前半部分去找。
#include
int low,high,i,mid;
cout<<\:\ //输入10个有序数 for(i=0;i
cout<<\ //输入要查找的数
cin>>b;
low=0; //设置查找的区间,开始时是全部 high=i-1;
mid=(low+high)/2;
while(a[mid]!=b&&low
if (b==a[mid]) //找到 cout<
else //没找到 cout<<\}
运行结果:
Input sort array a[10]: 10 12 14 16 18 20 22 24 26 28
Input number b: 16 16 is on 3 (2)
解:解法一
#include
{ char str1[N],str2[N],str[2*N];
cout<<\ first String\ cin>>str1;
cout<<\ second String\ cin>>str2; strcpy(str,str1);
strcat(str,str2);
cout<<\}
解法二
#include
{ char str1[N],str2[N],str[2*N]; int i,j;
cout<<\ first String\ cin>>str1;
cout<<\ second String\ cin>>str2; i=0;
while(str1[i]!=0) { str[i]=str1[i]; i++;
}
j=0;
while(str2[j]!=0) { str[i]=str2[j]; i++; j++; }
str[i]=0;
cout<<\}
运行结果:
Input first String abcde
Input second String
fghij
str=abcdefghij (3)
#include
{ int c[N][N],m,n,k,m1,n1,nm1; for(n=1;n for(n=3; n for(m=2; m<=n-1;m++) c[n][m]=c[n-1][m-1]+c[n-1][m]; //数组元素赋值 for(n=1; n { if(n%2==0)cout<<” ” ; //调整数字对齐 for (m=0;m<(N-n)/2;m++) //输出空格 cout< for(m=1;m<=n;m++) cout< #include { float s[M][N],sum,ave,temp,max,min; int i,j,k; cout<<\ for (i=0;i for (i=0;i //输入数据 //输入5个学生的学号与3门课成绩 //处理数据 //计算每个学生的总成绩 { sum=0.0; for (j=1;j sum=sum+s[i][j]; s[i][N-1]=sum; } for (j=1;j s[M-1][j]=min; s[M-2][j]=max; //计算每个学生的总分 //处理数据 //处理计算每门课程 //计算每门课程的最低分 //计算每门课程的最高分 } for (i=0;i { k=i; for(j=i+1;j if (s[k][N-1] for (j=0;j } cout< { for (j=0;j //输出数据 //输出学号、3门课程的成绩与总分 if (i==M-2 && j==0) cout< } cout<<\} 运行结果: Input data: 1001 90 80 85 1002 70 75 80 1003 65 70 75 1004 85 50 60 1005 80 90 70 Num. Math. Chin. Engl. Sum. ------------------------------ 1001 90 80 85 255 1005 80 90 70 240 1002 70 75 80 225 1003 65 70 75 210 1004 85 50 60 195 最高分 90 90 85 255 最低分 65 50 60 195 ------------------------------
相关推荐: