C++程序设计习题答案第六章
C++面向对象程序设计第六章课后习题答案
第六章课后习题答案(第二版谭浩强)1://xt6-1/cpp#include <iostream> //如用VC++应改为∶#include <iosttram.h>using namespace std; //如用VC++应取消此行#include "cylinder.h"#include "point.cpp"#include "circle.cpp"#include "cylinder.cpp"int main(){Cylinder cy1(3.5,6.4,5.2,10);cout<<"\noriginal cylinder:\nx="<<cy1.getX()<<", y="<<cy1.getY()<<", r="<<cy1.getRadius()<<",h="<<cy1.getHeight()<<"\narea="<<cy1.area()<<", volume="<<cy1.volume()<<endl;cy1.setHeight(15);cy1.setRadius(7.5);cy1.setPoint(5,5);cout<<"\nnew cylinder:\n"<<cy1;Point &pRef=cy1;cout<<"\npRef as a point:"<<pRef;Circle &cRef=cy1;cout<<"\ncRef as a Circle:"<<cRef;return 0;}3:解法一#include <iostream>using namespace std;class Point{public:Point(float a,float b):x(a),y(b){}~Point(){cout<<"executing Point destructor"<<endl;}private:float x;float y;};class Circle:public Point{public:Circle(float a,float b,float r):Point(a,b),radius(r){} ~Circle(){cout<<"executing Circle destructor"<<endl;} private:float radius;};int main(){Point *p=new Circle(2.5,1.8,4.5);delete p;return 0;}3:解法二#include <iostream>using namespace std;class Point{public:Point(float a,float b):x(a),y(b){}~Point(){cout<<"executing Point destructor"<<endl;} private:float x;float y;};class Circle:public Point{public:Circle(int a,int b,int r):Point(a,b),radius(r){}~Circle(){cout<<"executing Circle destructor"<<endl;} private:float radius;};int main(){Point *p=new Circle(2.5,1.8,4.5);Circle *pt=new Circle(2.5,1.8,4.5);delete pt;return 0;}3:解法三#include <iostream>using namespace std;class Point{public:Point(float a,float b):x(a),y(b){}virtual ~Point(){cout<<"executing Point destructor"<<endl;}private:float x;float y;};class Circle:public Point{public:Circle(float a,float b,float r):Point(a,b),radius(r){}virtual ~Circle(){cout<<"executing Circle destructor"<<endl;}private:float radius;};void main(){Point *p=new Circle(2.5,1.8,4.5);delete p;}4:#include <iostream>using namespace std;//定义抽象基类Shapeclass Shape{public:virtual double area() const =0; //纯虚函数};//定义Circle类class Circle:public Shape{public:Circle(double r):radius(r){} //结构函数virtual double area() const {return 3.14159*radius*radius;};//定义虚函数protected:double radius; //半径};//定义Rectangle类class Rectangle:public Shape{public:Rectangle(double w,double h):width(w),height(h){} //结构函数virtual double area() const {return width*height;} //定义虚函数protected:double width,height; //宽与高};class Triangle:public Shape{public:Triangle(double w,double h):width(w),height(h){} //结构函数virtual double area() const {return 0.5*width*height;}//定义虚函数protected:double width,height; //宽与高};//输出面积的函数void printArea(const Shape &s){cout<<s.area()<<endl;}//输出s的面积int main(){Circle circle(12.6); //建立Circle类对象circlecout<<"area of circle =";printArea(circle);//输出circle的面积Rectangle rectangle(4.5,8.4); //建立Rectangle类对象rectanglecout<<"area of rectangle =";printArea(rectangle);//输出rectangle的面积Triangle triangle(4.5,8.4); //建立Triangle类对象cout<<"area of triangle =";printArea(triangle); //输出triangle的面积return 0;}5:#include <iostream>using namespace std;//定义抽象基类Shapeclass Shape{public:virtual double area() const =0; //纯虚函数};//定义Circle(圆形)类class Circle:public Shape{public:Circle(double r):radius(r){}//结构函数virtual double area() const {return 3.14159*radius*radius;};//定义虚函数protected:double radius; //半径};//定义Square(正方形)类class Square:public Shape{public:Square(double s):side(s){} //结构函数virtual double area() const {return side*side;} //定义虚函数protected:double side;};//定义Rectangle(矩形)类class Rectangle:public Shape{public:Rectangle(double w,double h):width(w),height(h){} //结构函数virtual double area() const {return width*height;} //定义虚函数protected:double width,height; //宽与高};//定义Trapezoid(梯形)类class Trapezoid:public Shape{public:Trapezoid(double t,double b,doubleh):top(t),bottom(t),height(h){} //结构函数virtual double area() const {return0.5*(top+bottom)*height;} //定义虚函数protected:double top,bottom,height; //上底、下底与高};//定义Triangle(三角形)类class Triangle:public Shape{public:Triangle(double w,double h):width(w),height(h){} //结构函数virtual double area()const {return 0.5*width*height;}//定义虚函数protected:double width,height; //宽与高};int main(){Circle circle(12.6); //建立Circle类对象circleSquare square(3.5); //建立Square类对象squareRectangle rectangle(4.5,8.4); //建立Rectangle类对象rectangleTrapezoid trapezoid(2.0,4.5,3.2); //建立Trapezoid类对象trapezoidTriangle triangle(4.5,8.4); //建立Triangle类对象Shape*pt[5]={&circle,&square,&rectangle,&trapezoid,&triangle};//定义基类指针数组pt,使它每一个元素指向一个派生类对象double areas=0.0; //areas为总面积for(int i=0;i<5;i++){areas=areas+pt[i]->area();}cout<<"totol of all areas="<<areas<<endl; //输出总面积return 0;}(学习的目的是增长知识,提高能力,相信一分耕耘一分收获,努力就一定可以获得应有的回报)。
C程序设计第六章答案
实验六数组练习6.2代码如下:#include <iostream>using namespace std;int main(){int num, max = 0, count = 1;//user input 6 numbersfor (int i = 0; i < 6; i++){cout << "Enter a number: ";cin >> num;//if number entered > max, max = num, count = 1 again.if (num > max){max = num;count = 1;}else if (num == max){count++;}}//displaycout << "The largest number is " << max <<endl;cout << "The largest number appears " << count << " times\n";return 0;}练习6.4代码如下:#include <iostream>using namespace std;int main (){int score[40];int upcount = 0, downcount = 0, equalcount = 0, count = 0,i = 0, j = 0, sum = 0;//input the arrays, and when user enter a minus, stop inputingdo{cout << "Please enter less than 40 students' score, if you want to stop entering you can enter a minus.\n";cout << "You have entered " << count << " scores\n";cin >> j;if ((j >= 0) && (j <= 100)){score[i] = j;j++;count++;i++;}else if (j > 100){cout << "You should enter a correct score";}}while (j >= 0);//compute the sum of the arraysfor (i = 0; i < count; i++){sum += score[i];}//compute the averageint average = sum / count;for (i = 0; i < count; i++){if (score[i] > average){upcount++;}else if (score[i] == average){equalcount++;}else if (score[i] < average){downcount++;}}//display the resultcout << "The summer scores among " << count << " students is " << sum << endl;cout << "The average scores among " << count << " students is "<< average << endl;cout << "There are(is) " << upcount << " student's(s') scores are(is) higher than average.\n";cout << "There are(is) " << equalcount << " student's(s') scores are(is) equal to average.\n";cout << "There are(is) " << downcount << " student's(s') scores are(is) lower than average.\n";return 0;}练习6.6代码如下:#include <iostream>#include <iomanip>using namespace std;bool isPrime (int num);int main (){int prime[50];for (int i = 0, num = 2; i < 50; num++){if ( isPrime(num) ){prime[i] = num;i++;}}for (int i = 0, count = 0; i < 50; i++){cout << setw(6) << prime[i];count++;if (10 == count){cout << endl;count = 0;}}system("pause");return 0;}//this function called isPrime is used to judge an integer is prime or not... bool isPrime (int num){bool isPrime = true;for (int i = 2; i <= sqrt( (double)num ); i++){if (0 == num %i){isPrime = false;break;}}return isPrime;}练习6.8代码如下:#include <iostream>using namespace std;int average(int array[], int size);double average(double array[], int size);int main (){int array1[6] = {1,2,3,4,5,6};double array2[7] = {6.0,4.4,1.9,2.9,3,4,3.5};//display the resultcout << average(array1,6) << endl << average(array2,7) << endl;return 0;}//the kind of integerint average(int array[], int size){double sum = 0;for (int i = 0; i < size; i++){sum += array[i];}return sum / size;}//the kind of integerdouble average(double array[], int size) {double sum = 0;for (int i = 0; i < size; i++){sum += array[i];}return sum / size;}练习6.10代码如下:#include <iostream>using namespace std;void min (int array[], int size);int main (){int array[8] = {2,2,4,5,10,100,2,2};min(array,8);return 0;}//打印最小元的下标void min (int array[], int size){int min = array[0];int xiabiao[10];int j = 0;for (int i = 0; i < size; i++){if ( array[i] <= min ){min = array[i];xiabiao[j] = i;j++;}}int k = j;j = 0;//保存最小元下标的个数cout << "The min of the array(s) is " << min << endl;cout << "The subscript of the minnest number is(are) ";for (; j < k; j++){cout << xiabiao[j] << endl;}}练习6.12代码如下:#include <iostream>using namespace std;void reverse (int soure[], int size);//swapvoid reverse (int soure[], int size){for (int i = 0; i < (size / 2); i++){swap ( soure[i], soure[size-1-i] );}}//check the void reverse is right or notint main (){int array[6] = {1,2,3,4,5,6};reverse (array, 6);for (int i = 0; i < 6; i++){cout << array[i] << endl;}return 0;}练习6.14代码如下:#include <iostream>#include <ctime>using namespace std;int main (){int num[100000];srand ( time(0) );for (long i = 0; i < 100000; i++){num[i] = rand();}//生成关键字int key = rand();cout << "关键字是" << key << endl;//开始计时long startTime1 = time(0);for (int i = 0; i < 100000; i++){if (key == num[i]){cout <<"关键字的下标是"<< i <<endl;}}long endTime1 = time(0);long time1 = endTime1 - startTime1;cout << "顺序搜索时间是" << time1 <<"秒\n\n";//二分搜索int low = 0;int high = 99999;//对数组进行排序,现在开始第二次计时long startTime2 = time(0);for (long i = 9999;i >= 1; i--){int xiabiao = 0, lagest = num[0];for (long j = 1;j <= i; j++){if ( num[j] > lagest ){lagest = num[j];xiabiao = j;}}//swapif ( xiabiao != i){num[xiabiao] = num[i];num[i] = lagest;}}while (high >= low){int mid = (low + high) / 2;if (key < num[mid]){high = mid - 1;}else if (key == num[mid]){cout << "关键字下标是" << mid << endl;break;}else{low = mid + 1;}}long endTime2 = time(0);long time2 = endTime2 - startTime2;cout << "排序和二分搜索花费时间是" << time2 << "秒\n\n";system("pause");return 0;}练习6.16代码如下:#include <iostream>using namespace std;void turn ( double arrays[], int size);int main (){double arrays[7] = {6.0,4.4,1.9,2.9,3.4,2.9,3.5};turn(arrays, 7);for (int i = 0; i < 7; i++){cout << arrays[i] << " ";}system("pause");return 0;}//起泡排序void turn ( double arrays[], int size){bool changed = true;do{changed = false;for (int i = 0; i < size - 1; i++){if (arrays[i] > arrays[i+1]){swap(arrays[i], arrays[i+1]);changed = true;}}} while (changed);}练习6.18代码如下:#include <iostream>using namespace std;int main (){int arrays[4][4] = {{1,2,4,5},{6,7,8,9},{10,11,12,13},{14,15,16,17}};int sum = 0;for (int i = 0, j = 0; i < 4; i++,j++){sum += arrays[i][j];}cout << "主对角线之和为" << sum << endl;system("pause");return 0;}练习6.20代码如下:#include <iostream>using namespace std;void turn ( int arrays[], int size);int main(){int time[8][7] = {{2,4,3,4,5,8,8},{7,3,4,3,3,4,4},{3,3,4,3,3,2,2},{9,3,4,7,3,4,1},{3,5,4,3,6,3,8},{3,4,4,6,3,4,4},{3,7,4,8,3,8,4},{6,3,5,9,2,7,9}};int sumofRow[8] = {0,0,0};for (int row = 0; row < 8; row++){for (int i = 0; i < 7; i++){sumofRow[row] += time[row][i];}}turn(sumofRow, 8);for (int i = 7; i >= 0; i--){cout << sumofRow[i] << endl;}system("pause");return 0;}//排序void turn ( int arrays[], int size){bool changed = true;do{changed = false;for (int i = 0; i < size - 1; i++){if (arrays[i] > arrays[i+1]){swap(arrays[i], arrays[i+1]);changed = true;}}} while (changed);}练习6.22代码如下:#include <iostream>using namespace std;//compute the sumvoid mutiplyMatrix (int a[][5],int b[][5],int c[][5],int rowsize){for (int i = 0; i < rowsize; i++){for (int j = 0; j < rowsize; j++){for (int k = 0; k < rowsize; k++){c[i][j] += (a[i][k] + b[k][j]);}}}}int main (){int a[5][5] = {{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};int b[5][5] = {{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};int c[5][5] = {{0,0,0,0,0},{0},{0},{0},{0}};mutiplyMatrix(a,b,c,5);for (int i = 0; i < 5; i++){for (int j = 0; j < 5; j++){cout << c[i][j] << endl;}}system("pause");return 0;}练习6.24代码如下:#include <iostream>#include <ctime>using namespace std;int main(){srand( time(0) );int chess[8][8];//随机输入0和1,并输出8*8列表for (int i = 0; i < 8; i++){for (int j = 0; j < 8; j++){chess[i][j] = rand() % 2;cout << chess[i][j];}cout << endl;}//计算每行的和for (int row = 0; row < 8; row++){int sumofrow = 0;for (int column = 0; column < 8; column++){sumofrow += chess[row][column];}if (0 == sumofrow){cout << "All 0s on row" << row + 1 << endl;}else if (8 == sumofrow){cout << "All 1s on row" << row + 1 << endl;}}//计算每列的和for (int column = 0; column < 8; column++){int sumofcolumn = 0;for (int row = 0; row < 8; row++){sumofcolumn += chess[row][column];}if (0 == sumofcolumn){cout << "All 0s on column" << column + 1 << endl;}else if (8 == sumofcolumn){cout << "All 1s on column" << column + 1 << endl;}}//计算两个对角线的和int sumofsubdiagonal1 = 0, sumofsubdiagonal2 = 0;for (int row = 0, column = 0; row < 8; row++,column++){sumofsubdiagonal1 += chess[row][7 - column];sumofsubdiagonal2 += chess[row][column];}if ( 0 == sumofsubdiagonal1 ){cout << "All 0s on subdiagonal1" << endl;}else if ( 8 == sumofsubdiagonal1 ){cout << "All 1s on subdiagonal1" << endl;}if ( 0 == sumofsubdiagonal2 ){cout << "All 0s on subdiagonal2" << endl;}else if ( 8 == sumofsubdiagonal2 ){cout << "All 1s on subdiagonal2" << endl;}system("pause");return 0;}练习6.26代码如下:#include <iostream>using namespace std;int factors(int num, int table[][2]){/*从i=2开始除,若不能被i整除则i++;若能被i整除则输出i,且num变成num除以i的商,重新把2赋值给i,循环。
面向对象程序设计 C 山师 第六章习题答案
第六章习题答案一、选择填空1、A2、C3、D4、B5、D6、A7、C8、A9、D 10、A 11、C 12、A13、B 14、C 15、C 16、D 17、B 18、C 19、A 20、D21、C 22、B二、判断下列描述的正确性,对者划√,错者划×。
1、√2、×3、×4、×5、√6、√7、×8、√9、× 10、√11、√ 12、√ 13、√ 14、√ 15、× 16、√ 17、√ 18、√ 19、√ 20、×21、× 22、×三、分析下列程序的输出结果。
1、运行该程序输出结果如下所示。
Default constructor calledConstructor calleda=0,b=0a=4,b=82、运行该程序输出结果如下所示。
a=7,b=93、运行该程序输出结果如下所示。
1044、运行该程序输出结果如下所示。
1035,789.5045、运行该程序输出结果如下所示。
1{}{0,1,2,3,4,5,6,7,8}1{11,12,13,14,15,16,17,18,19}{19,18,17,16,15,14,13,12,11}6、运行该程序输出结果如下所示。
Starting1:Default constructor called.Default constructor called.Default constructor called.Eding1:Starting2:Constructor: a=5,b=6Constructor: a=7,b=8Constructor: a=9,b=10Ending2:Destructor called.a=9,b=10Destructor called.a=7,b=8Destructor called.a=5,b=6Destructor called.a=5,b=6Destructor called.a=3,b=4Destructor called.a=1,b=27、运行该程序输出结果如下所示。
C语言程序设计(第3版)第6章习题参考答案
gets(stridiom1);
printf("\nplease input the second idiom: ");
gets(stridiom2);
fnConcat(stridiom1,stridiom2);
printf("\nthe result is: %s",stridiom1)=0;
while(b[j] != '\0') /*把第二个字符串的内容连接到第一个字符串的后面*/
{
a[i+j] = b[j];
j++;
}
a[i+j]= '\0'; /*添加字符串结束符*/
}
void main()
{ char stridiom1[80],stridiom2[80];
i++;
}
a[j]= '\0'; /*添加字符串结束符*/
}
void main()
{ char stridiom1[80];
printf("\nplease input the first idiom: ");
gets(stridiom1);
fnConvert(stridiom1);
printf("\nthe result is: %s",stridiom1);
scanf("%d",&n);
printf("%ld",fnF(n));
getch();
}
(4)编一函数判别某一数是否为素数,若是,返回值为1,否则,返回值为0。
C语言程序设计第六章数组习题及答案
1.以下对一维整型数组a的定义,正确的是_。
(2分)A.int a(10) ;B.int n = 10 , a[n] ;C.int n ;scanf( "%d" , &n ) ;int a[n] ;D.int a[10] ;2.若有定义:int a[10] ;,则对a数组元素的正确引用是_。
(2分)A.a[10]B.a[3.5]C.a(5)D.a[10-10]3.对定义int a[10] = {6 , 7 , 8 , 9 , 10} ; 的正确理解是_。
(2分)A.将5个初值依次赋给a[1]--a[5]B.将5个初值依次赋给a[0]--a[4]C.将5个初值依次赋给a[6]--a[10]D.因为数组长度与初值个数不相同,所以此语句不正确4..若有定义:int a[3][4]; , 则对a数组元素的正确引用是_。
(2分)A.a[3][4]B.a[1,3]C.a[1+1][0]D.a(2)(1)5.以下对二维数组a初始化正确的语句是_。
(2分)A.int a[2][ ]={{0 , 1 , 2}, {3 , 4 , 5}};B.int a[ ][3]={{0, 1, 2}, {3, 4, 5}};C.int a[2][4]={{0, 1 , 2}, {3 , 4}, {5}};D.int a[ ][3]={{0, 1, 2}, { }, {3, 4}};6.对二维数组a进行如下初始化:int a[ ][3]={0 , 1 , 2 , 3 , 4 , 5};则a[1][1]的值是_。
(2分)A.0B.3C.4D.17.下面程序段的运行结果是_。
(2分)#include<stdio.h>int main( ){int i , x[3][3] = {1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9} ;for( i = 0 ; i < 3 ; i++ )printf( "%2d" , x[i][2-i] ) ;return 0 ;}A.1 5 9B.1 4 7C.3 5 7D.3 6 98.以下对数组s的初始化,错误的是_。
游洪跃C语言程序设计第6章 习题解答
break;
case 2:/* 2月份*/
return 31 + dt.day;
break;
case 3:/* 3月份*/
if (IsLeapYear(dt.year))
{/*闰年*/
return 31 + 29 + dt.day;
}
else
{/*平年*/
return 31 + 28 + dt.day;
}
else
{/*平年*/
return 31 + 28 + 31 + 30 + 31 + dt.day;
}
break;
case 7:/* 7月份*/
if (IsLeapYear(dt.year))
{/*闰年*/
return 31 + 29 + 31 + 30 + 31 + 30 + dt.day;
}
else
答案:A
7.有以下程序:
/*文件路径名:ex5_1_7\main.c */
#include <stdio.h>/*标准输入/输出头文件*/
int main(void)/*主函数main() */
{
int c = 168;/*定义变量*/
printf("%d\n", c | c);/*输出c | c */
{/*闰年*/
return 31 + 29 + 31 + 30 + dt.day;
}
else
{/*平年*/
return 31 + 28 + 31 + 30 + dt.day;
c 程序设计教程习题6_8章参考答案
习题及实验解答第六章一、选择题1、应为4(无正确选项)2、D3、B C4、D5、A6、A7、C8、B9、A 10、A二、程序填空1、stu[i].score k=j p[k]=p[i] p[i]=temp2、p!=NULL p->data p->next3、struct node * s->data=ch r=s NULL三、编程题1、#include "iostream.h"struct staff{char num[6];char name[8];float salary[3]; //分项工资float gs; //实得工资}s[100];void main( ){int i,j,n;cin>>n; /*输入职工人数*/for(i=0;i<n;i++){cin>>s[i].num>>s[i].name;for(j=0;j<3;j++)cin>>s[i].salary[j];}cout<<"NO. salary\n";for(i=0;i<n;i++){s[i].gs= s[i].salary[0]+ s[i].salary[1]- s[i].salary[2] ;cout<<s[i].num<<'\t'<<s[i].gs<<endl;}}2、#include "iostream.h"#include "stdio.h"struct str{char ch;struct str *next;};void main(){char s[100];int i=0,num=0;struct str *insert,*head=NULL,*p;gets(s);while(s[i]!='\0'){insert=new str;insert->ch=s[i];if(head==NULL){head=insert ;head->next=NULL;}else{insert->next=head ;head=insert;}i++;}p=head;while(p!=NULL){if(p->ch>='A'&&p->ch<='Z')num++;cout<<p->ch;p=p->next;}cout<<endl<<"num="<<num<<endl; }3、#include "iostream.h"#include "stdio.h"struct node{char ch;int count;struct node *next;};void main( ){struct node *head,*p1,*p2,*insert;char c;head=NULL;while((c=getchar())!='\n'){p1=head;while(p1!=NULL&&c>p1->ch){p2=p1;p1=p1->next;}if(p1==NULL){insert=new node;insert->ch=c;insert->count=1;if(head==NULL){insert->next=head;head=insert;}else{insert->next=NULL;p2->next=insert;}}else if(c==p1->ch)p1->count++;else{insert=new node;insert->ch=c;insert->count=1;if(p1==head){insert->next=head;head=insert;}else{insert->next=p1;p2->next=insert;}}}p1=head;while(p1!=NULL){cout<<p1->ch<<' '<<p1->count<<'\t';p1=p1->next;}}4、#include "stdio.h"#include "iostream.h"struct node{int coef;int expn;struct node *next;};struct node *creat(){struct node *head,*tail,*p;int c,e;head=NULL;cin>>c>>e;while(c!=0) //约定以输入系数为0作为多项式的结束{p=new node;p->coef=c;p->expn=e;if(head==NULL)head=p;elsetail->next=p;tail=p;cin>>c>>e;}tail->next=NULL;return head;}void print(struct node *h){struct node *p;p=h;while(p!=NULL){if(p->next!=NULL)cout<<p->coef<<'x'<<p->expn<<'+';else{if(p->coef!=0&&p->expn!=0)cout<<p->coef<<'x'<<p->expn<<endl;else if(p->coef!=0)cout<<p->coef<<endl;elsecout<<endl;}p=p->next;}}void main(){struct node *h1,*p1,*h2,*p2,*h3,*p3,*newnode,*t3;h1=creat();print(h1);h2=creat();print(h2);p2=h2;h3=NULL;p1=h1;p2=h2;p3=h3;t3=h3;while(p1!=NULL&&p2!=NULL){newnode=new node;if(p1->expn>p2->expn){newnode->coef=p1->coef;newnode->expn=p1->expn;p1=p1->next;}else if(p1->expn<p2->expn){newnode->coef=p2->coef;newnode->expn=p2->expn;p2=p2->next;}else{newnode->coef=p2->coef+p1->coef;newnode->expn=p2->expn;p2=p2->next;p1=p1->next;}if(h3==NULL){h3=newnode;t3=newnode;}elset3->next=newnode;t3=newnode;}if(p1==NULL)t3->next=p2;elset3->next=p1;print(h3);}第七章一、选择题1、D2、B3、B4、A5、B6、A7、D8、B9、C 10、B二、程序填空1、fname, “w”(ch=getchar())!=’#’count++2、(c=fgetc(fp)) length++ length=03、”wb”&emp, sizeof(employer),1,fp fclose(fp) “rb”&emp, sizeof(employer),1,fp三、编程题1、#include "iostream.h"#include "stdlib.h"#include "stdio.h"void main(){FILE *fp1,*fp2;char ch;fp1=fopen("f1.txt","a");if(fp1==NULL){cout<<"can't open f1.\n";exit(1);}if((fp2=fopen("f2.txt","r"))==NULL){cout<<"can't open f2.\n";exit(1);}while(1){ch=fgetc(fp2);if(feof(fp2))break;cout<<ch;fputc(ch,fp1);}fclose(fp1);fclose(fp2);}2、#include "iostream.h"#include "stdlib.h"#include "stdio.h"void main(){FILE *fp;int a[10],i,j;if((fp=fopen("d1.dat","w"))==NULL){cout<<"can't open d1.\n";exit(1);}for(i=0;i<10;i++)a[i]=rand();for(i=0;i<9;i++)for(j=0;j<9-i;j++)if(a[j]<a[j+1]){int t=a[j];a[j]=a[j+1];a[j+1]=t;}for(i=0;i<10;i++)fprintf(fp,"%d\t",a[i]);fclose(fp);}3、#include "iostream.h"#include "stdlib.h"#include "stdio.h"#include "string.h"void main(){FILE *fp;char s[100];int a[26]={0},i;if((fp=fopen("f.txt","r"))==NULL){cout<<"can't open f.\n";exit(1);}fgets(s,100,fp);strlwr(s);i=0;while(s[i]!='\0'){if(s[i]>='a'&&s[i]<='z')a[s[i]-'a']++;i++;}for(i=0;i<26;i++)cout<<(char)('a'+i)<<":"<<a[i]<<endl;fclose(fp);}4、#include "iostream.h"#include "stdlib.h"#include "stdio.h"struct student{char num[8];char name[20];double s[3],ave;}st[5];void main(){student stu[5];FILE *fp;int i;if((fp=fopen("stu","wb"))==NULL){cout<<"can't open stu.\n";exit(1);}for(i=0;i<5;i++){cin>>stu[i].num>>stu[i].name>>stu[i].s[0]>>stu[i].s[1]>>stu[i].s[2];stu[i].ave=(stu[i].s[0]+stu[i].s[1]+stu[i].s[2])/3;}fwrite(stu,sizeof(student),5,fp);fclose(fp);}第八章一、选择题1、A2、A3、C4、C5、6、D7、B8、D9、C 10、B11、D 12、A 13、B 14、D 15、D二、阅读程序写结果1、con1 calledcon2 calledcon3 calleda=0,b=0a=10,b=10a=10,b=202、0 51 52 53 54 53、4564、10,106,67,95、x=0x=10x=7三、编程题1、#include "iostream.h"#include "string.h"class Cat{private:int age;double weight;char color[10];public:void set(int a,double w,char c[10]){age=a;weight=w;strcpy(color,c);}void print(){cout<<"age:"<<age<<"\tweight:"<<weight<<"\color:"<<color<<endl;}int getage(){return age;}double getweight(){return weight;}char *getcolor(){return color;}};void main(){Cat c1;int a;double w;char c[10];cin>>a>>w>>c;c1.set(a,w,c);c1.print();}2、#include "iostream.h"#include "string.h"#include "stdio.h"class Mystring{private:char *str;public:Mystring(){ }Mystring(char *s){str=new char[100];strcpy(str,s);}void set(char *s){str=new char[100];strcpy(str,s);}void print(){cout<<str<<endl;}int length( ){int i=0;while(str[i]!='\0')i++;return i;}char *stringcat(Mystring s2){int i=0,j=0;while(str[i]!='\0')i++;while(s2.str[j]!='\0')str[i++]=s2.str[j++];str[i]='\0';return str;}};void main(){Mystring s1;char s[100];gets(s);s1.set(s);s1.print();gets(s);Mystring s2(s);s2.print();cout<<s1.stringcat(s2);}3、#include "iostream.h"#include "string.h"#include "stdio.h"class Point{private:double x,y;public:Point(){ }Point(double x1,double y1){x=x1;y=y1;}void set(double x1,double y1){x=x1;y=y1;}void move(double x1,double y1){x=x+x1;y=y+y1;}void print(){cout<<"("<<x<<","<<y<<")"<<endl;}double getx(){ return x;}double gety(){ return y;}};class Circle:public Point{private:double r;public:void set(double x1,double y1,double r1){Point::set(x1,y1);r=r1;}void print(){Point::print();cout<<r<<endl;}double getr(){ return r;}double s(){ return 3.14*r*r;}};void main(){Point p1;Circle c1;double x1,y1,r1;cin>>x1>>y1;p1.set (x1,y1);p1.print ();cin>>x1>>y1;p1.move (x1,y1);p1.print ();cin>>x1>>y1>>r1;c1.set (x1,y1,r1);c1.print ();cout<<c1.s()<<endl;}4、#include "iostream.h"class Point{private:int x,y;public:Point(){ }Point(int x1,int y1){ x=x1; y=y1;}friend Point operator+(Point &p1,Point &p2){Point p(p1.x+p2.x,p1.y+p2.y);return p;}void print(){cout<<"("<<x<<","<<y<<")"<<endl;}};void main(){Point p1(1,2),p2(2,3),p3;p3=p1+p2;p3.print();}5、#include "iostream.h"#include "stdio.h"#include "string.h"class Teacher{private:char name[20];public:void virtual input(){cout<<"input name:";cin>>name;}virtual double wage()=0;void virtual print(){cout<<name<<'\t';}};class Professor:public Teacher{private:int cnum; //课时数public:void input(){Teacher::input ();cout<<"input cnum:";cin>>cnum;}double wage(){return (3000+40*cnum);}void print(){Teacher::print ();cout<<wage()<<endl;}};class ViceProfessor:public Teacher {private:int cnum; //课时数public:void input(){Teacher::input ();cout<<"input cnum:";cin>>cnum;}double wage(){return (2500+30*cnum);}void print(){Teacher::print ();cout<<wage()<<endl;}};class Lecture:public Teacher{private:int cnum; //课时数public:void input(){Teacher::input ();cout<<"input cnum:";cin>>cnum;}double wage(){return (2000+25*cnum);}void print(){Teacher::print ();cout<<wage()<<endl;}};void main(){Teacher *t;Professor *p;ViceProfessor *vp;Lecture *l;char ptitle[20],ch;//职称do{cout<<"input ptitle(professor,viceprofessor or lecture):"<<endl;gets(ptitle);if(!strcmp(ptitle,"professor")){p=new Professor;t=p;}else if(!strcmp(ptitle,"viceprofessor")){vp=new ViceProfessor;t=vp;}else{l=new Lecture;t=l;}t->input ();t->print ();cout<<"continue(y/n)?";cin>>ch;}while(ch=='y');}。
C语言程序设计(第二版)-习题答案 第6章习题答案
《C语言程序设计(Visual C++6.0环境)》习题答案习题六一、思考题1、编写程序,将10个整形数2、4、6,…18,20赋给一个数组,然后使用指针输出显示该数组各元素的值。
#include “stdio.h”main(){int i,*p;int a[10]={2,4,6,8,10,12,14,16,18,20};p=a;for(i=0;i<10;i++)printf(“%3d”,*(p+i));}2、编写程序,将两个字符串连接起来。
#include<stdio.h>#define N 120main(){ char s1[N+N],s2[N],*p,*q;printf("输入2个字符串\n");scanf("%s%s",s1,s2);for(p=s1;* p!='\0'; p++);for(q=s2;*p++=*q++;);printf("两字符串连接后:%s\n",s1);}3、输入5个字符串,按英文字典排序从小到大顺序输出。
#include "stdio.h"#include "string.h"void sort(char *name[],int count){char *temp;int i,j,min;for(i=0;i<count-1;i++){min=i;for(j=i+1;j<count;j++)if(strcmp(name[min],name[j])>0)min=j;if(min!=i){temp=name[i];name[i]=name[min];name[min]=temp;}}}main(){char *name[5]={"BASIC","FORTRON","PASAL","C","FOXBASE"};int i=0;sort(name,5);for(;i<5;i++)printf("%s\n",name[i]);}4、编一程序,输入月份号,输出该月的英文月名。
C语言程序设计第四版第六章答案_谭浩强
C语言程序设计第四版第六章答案_谭浩强1、用筛选法求100之内的素数。
解:#include#includeint main(){int i,j,n,a[101];for (i=1;i<=100;i++)a[i]=i;a[1]=0;for (i=2;i<sqrt(100);i++)< bdsfid="73" p=""></sqrt(100);i++)<>for (j=i+1;j<=100;j++){if(a[i]!=0 && a[j]!=0)if (a[j]%a[i]==0)a[j]=0;}printf("\");for (i=2,n=0;i<=100;i++){ if(a[i]!=0){printf("%5d",a[i]);n++;}if(n==10){printf("\");n=0;}}printf("\");return 0;}2、用选择法对10整数排序。
解:#includeint main(){int i,j,min,temp,a[11];printf("enter data:\");for (i=1;i<=10;i++){printf("a[%d]=",i);scanf("%d",&a[i]);}printf("\");printf("The orginal numbers:\");for (i=1;i<=10;i++)printf("%5d",a[i]);printf("\");for (i=1;i<=9;i++){min=i;for (j=i+1;j<=10;j++)if (a[min]>a[j]) min=j;temp=a[i];a[i]=a[min];a[min]=temp;}printf("\The sorted numbers:\");for (i=1;i<=10;i++)printf("%5d",a[i]);printf("\");return 0;}3、求一个3×3的整型矩阵对角线元素之和。
C程序设计(第五版)-第6章利用数组处理批量数据课后习题答案
C程序设计(第五版)-第6章利⽤数组处理批量数据课后习题答案1.⽤筛选法求100质数⼜称素数。
⼀个⼤于1的⾃然数,除了1和它⾃⾝外,不能被其他⾃然数整除的数叫做质数;否则称为合数(规定1既不是质数也不是合数)先解释⼀下筛选法的步骤:<1> 先将1挖掉(因为1不是素数)。
<2> ⽤2去除它后⾯的各个数,把能被2整除的数挖掉,即把2的倍数挖掉。
<3> ⽤3去除它后⾯的各数,把3的倍数挖掉。
<4> 分别⽤5…各数作为除数去除这些数以后的各数。
上述操作需要⼀个很⼤的容器去装载所有数的集合,只要满⾜上述条件,即2的倍数⼤于1的全部置0,3的倍数⼤于1的全部置0,4的倍数⼤于1的全部置0……⼀直到这个数据集合的末尾,这样⼀来不为0的数就是素数了,然后按下标在⾥⾯进⾏查找就好了1#include <stdio.h>2#include <windows.h>3int main()4{5printf("------------------\n");6int i, j, k, a[100];7// 先给100个数赋值8for (i = 0; i < 100; i++)9{10a[i] = i + 1;11}1213// 1不是质数也不是合数14a[0] = 0;1516for (i = 0; i < 100; i++)17{18for (j = i + 1; j < 100; j++)19{20// 把后⾯的数能整除前⾯的数赋值为021if (a[i] != 0 && a[j] != 0)22{23if (a[j] % a[i] == 0)24{25a[j] = 0; //把不是素数的都赋值为026}27}28}29}3031// 打印质数,每10个换⾏32for (i = 0; i < 100; i++)33{34if (k % 10 == 0)35{36printf("\n");37}38if (a[i] != 0)39{40printf("%d ", a[i]);41k++;42}43}4445return 0;46}2.⽤选择法对101#include <stdio.h>2#include <windows.h>3int main()4{5printf("请输⼊10个数:\n");6int minIndex, temp, a[10];78for (int i = 0; i < 10; i++)9{10scanf("%d", &a[i]);11}1213for (int i = 0; i < 10; i++)14{15minIndex = i;16for (int j = i + 1; j < 10; j++)17{18if (a[j] <= a[minIndex])19{20minIndex = j;21}22}2324temp = a[i];25a[i] = a[minIndex];26a[minIndex] = temp;27}2829printf("排序后结果:\n");3031for (int i = 0; i < 10; i++)32{33printf("%d ", a[i]);34}35return 0;36}3.求⼀个3*31#include <stdio.h>2#include <windows.h>3int main()4{5printf("请输⼊元素:\n");6int x, y, z, a[3][3];7for (int i = 0; i < 3; i++)8{9for (int j = 0; j < 3; j++)10{11scanf("%d", &a[i][j]);12}13}14printf("输出刚刚输⼊的元素:\n");15for (int i = 0; i <= 2; i++)16{17for (int j = 0; j <= 2; j++)18{19printf("%d\t", a[i][j]);20}2122printf("\n");23}24printf("\n");25// 计算对⾓线的合26for (int i = 0; i < 3; i++)27{28x += a[i][i];29}3031for (int i = 0, j = 2; i < 3; i++, j--)32{33y += a[i][j];34}35z = x + y;36printf("左上到右下对⾓线的合:%d\n", x); 37printf("右上到左下对⾓线的合:%d\n", y); 38printf("两条对⾓线之合:%d\n", z);39// 结果40// 请输⼊元素:41// 1 2 3 4 5 6 7 8 942// 输出刚刚输⼊的元素:43// 1 2 344// 4 5 645// 7 8 94647// 左上到右下对⾓线的合:1548// 右上到左下对⾓线的合:3149// 两条对⾓线之合:4650return 0;51}4.1#include <stdio.h>2#include <windows.h>3int main()4{5printf("------------------\n");6int t, x, a[5] = {1, 2, 4, 5, 6};78printf("请输⼊需要插⼊的数字:\n");9scanf("%d", &x);10for (int i = 0; i < 5; i++)11{12if (x < a[i])13{14t = a[i];15a[i] = x;16x = t;17}18printf("%3d", a[i]);19}20printf("%3d", x);2122return 0;23}5.讲⼀个数组的值按逆序重新存放。
C语言程序设计教程第六章课后习题参考答案
C语⾔程序设计教程第六章课后习题参考答案P158 1求三个实数最⼤值#includefloat max(float,float,float);int main(){float a,b,c,m;printf("请输⼊三个实数:");scanf("%f %f %f",&a,&b,&c);printf("最⼤数为%f\n",max(a,b,c));return 0;}float max(float a,float b,float c){float t;if(a>b&&a>c)t=a;else if(b>a&&b>c)t=b;elset=c;return t;}P158 2求最⼤公约数最⼩公倍数#includeint fun1(int a,int b);int fun2(int a,int b);int main(){int a,b;printf("请输⼊两个整数:");scanf("%d %d",&a,&b);printf("最⼤公约数为:%d\n",fun1(a,b));int t,r;if(a{t=a;a=b;b=t;}while((r=(a%b))!=0) {a=b;b=r;}return b;}int fun2(int a,int b) {int n;n=(a*b)/fun1(a,b); return n;}P158 3求完全数#includevoid wan(int n); void main(){int n;for(n=1;n<1000;n++) wan(n);printf("\n");}void wan(int n){if(n%i==0)s=s+i;}if(n==s)printf("%d\t",n); }P158 4⽆暇素数#include#includeint nixvshu(int n);int isPrime(int n);int main(){int n,t;printf("⽆暇素数:\n");for(n=100;n<=999;n++) {t=nixvshu(n);if(isPrime(n)&&isPrime(t)) printf("%d\t",n);}printf("\n");return 0;}int nixvshu(int n){int x=0;while(n){x=x*10+n%10;n=n/10;}return x;int i;for(i=2;i<=sqrt(n);i++)if(n%i==0) return 0;return n;}P158 7递归函数#includeint Y(int n){if(n==0)return 0;if(n==1)return 1;if(n==2)return 2;elsereturn (Y(n-1)+Y(n-2)+Y(n-3)); } int main(){int n,k=0;for(n=0;n<=19;n++){printf("%d\t",Y(n));k++;if(k%5==0)printf("\n");}return 0;}P124 6分解质因数#include#includevoid fenjie(int );int main(){int n;printf("请输⼊⼀个正整数:"); scanf("%d",&n);if(isPrime(n)){printf("%d=1*%d\n",n,n);}else{fenjie(n);printf("\n");}return 0;}int isPrime(int n){int i;for(i=2;i<=sqrt(n);i++){if(n%i==0) return 0;}return 1;}int zhi(int n){int m;for(m=2;m<=n;m++){if(isPrime(m)&&(n%m==0)) break;void fenjie(int n){int m;printf("%d=%d",n,zhi(n));while(n>zhi(n)){m=zhi(n);n=n/m;printf("*%d",zhi(n));}}P47 1输出闰年#includeint f(int year);int main(){int year,k=0;for(year=1900;year<=2000;year++){if(f(year)){printf("%d\t",year);k++;if(k%5==0)printf("\n");}}return 0;}int f(int year){if((year%4==0&&year%100!=0)||(year%400==0)) return year;P47 2输出回⽂数#includeint fun(int n);int main(){int n,k=0;for(n=10;n<=2000;n++) {if(n == fun(n)){printf("%d\t",n);k++;if(k%5==0)printf("\n");}}return 0;}int fun(int n){int i=0;while(n>0){i=i*10+n%10;n=n/10;}return i;}P47 3进制转换#includevoid trans(int n,int base); int main()printf("请输⼊要转换的⼗进制数:"); scanf("%d",&n);printf("请输⼊转换的进制:"); scanf("%d",&base);trans(n,base);printf("\n");return 0;}(⽅法⼀)void trans(int n,int base){if(n){trans(n/base,base);if(n%base>=10)switch(n%base){case 10:printf("A");break;case 11:printf("B");break;case 12:printf("C");break;case 13:printf("D");break;case 14:printf("E");break;case 15:printf("F");break;}elseprintf("%d",n%base);}}(⽅法⼆)void trans(int n,int base){int r;char c;trans(n/base,base); r=n%base;if(r>=10)c='A'+r-10;elsec='0'+r;printf("%c",c);}}。
c++程序设计课后习题第6章答案
length = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
angle = atan( (y2-y1) / (x2-x1) );
angle = angle *180/3.141592653;
{
protected:
int n;
public:
void Show() {cout<<n<<endl;}
};
class Derived:public Base1,public Base2
{
public:
void Set(int x,int y) { m=x;n=y;}
//Derived类中重载show()方法
}
四、编程题
1.设计一个基类,从基类派生圆柱,设计成员函数输出它们的面积和体积。
#include < iostream >
using namespace std;
class Basic//基类
{
protected:
double r;
public :
Basic(){ r = 0; }
}
void printPoint()
{
cout<<"圆形直角坐标:("<< x <<", "<< y <<")"<< endl;
}
void printRadius()
{
cout<<"圆的半径:"<< r << endl;
c 程序设计教程习题6_8章参考答案
int getage()
{
return age;
}
double getweight()
{
return weight;
}
char *getcolor()
{
return color;
}
};
void main()
{
Cat c1;
int a;
double w;
char c[10];
cin>>a>>w>>c;
print(h3);
}
第七章
一、选择题
1、D2、B3、B4、A5、B
6、A7、D8、B9、C10、B
二、程序填空
1、fname,“w”(ch=getchar())!=’#’count++
2、(c=fgetc(fp))length++length=0
3、”wb”&emp, sizeof(employer),1,fpfclose(fp)“rb”
newnode->expn=p1->expn;
p1=p1->next;
}
else if(p1->expn<p2->expn)
{
newnode->coef=p2->coef;
newnode->expn=p2->expn;
p2=p2->next;
}
else
{
newnode->coef=p2->coef+p1->coef;
else
{
if(p->coef!=0&&p->expn!=0)
c程序设计第四版(谭浩强)第六章答案
# include<stdio.h># include<math.h># include<string.h>/*int main() //筛选法求100以内的素数{intp,m=0,i,j;for(i=2;i<100;i++){p=(int)sqrt(i);for(j=2;j<=p;j++)if(i%j==0)break;if(j==p+1){printf("%-3d",i);m+=1;}if(m%10==0)printf("\n");}putchar('\n');}void sort(int a[],int n) //选择法排序{inti,j,k;for(i=1;i<n;i++)for(j=i;j<n;j++)if(a[i-1]>a[j]){k=a[i-1];a[i-1]=a[j];a[j]=k;}}int main(){int a[10],i;printf("10 munber:");for(i=0;i<10;i++)scanf("%d",&a[i]);sort(a,10);printf("sort:");for(i=0;i<10;i++)printf("%-2d",a[i]);putchar('\n');}int main(){int a[3][3],i,j,s=0; //求对角线元素之和printf("输入矩阵:\n");for(i=0;i<3;i++)for(j=0;j<3;j++)scanf("%d",&a[i][j]);for(i=0;i<3;i++)s+=a[i][i];printf("对角线元素之和为:%d\n",s);}int main(){int a[]={1,2,3,4,6,7,8,9}; //向已排好序的数组插入新数ints,b,i,j;s=sizeof(a)/4;printf("enter number:");scanf("%d",&b);for(i=0;i<s;i++)if(b>a[i]&&i!=s-1)continue;else if(i==s-1)a[s]=b;else{for(j=s;j>i;j--)a[j]=a[j-1];a[i]=b;break;}printf("new sort:");for(i=0;i<=s;i++)printf("%-2d",a[i]);printf("\n");}int main(){int a[9]={1,2,3,4,5,6,7,8,9},i,n,t,l; //逆序输出l=sizeof(a)/4;n=l/2;for(i=0;i<=n;i++){t=a[i];a[i]=a[l-i-1];a[l-i-1]=t;}for(i=0;i<l;i++)printf("%d ",a[i]);putchar('\n');}int main(){int a[10][10],i,j; //杨辉三角for(i=0;i<10;i++)for(j=0;j<10;j++)if(j==0||i==j)a[i][j]=1;else if(i>j)a[i][j]=a[i-1][j-1]+a[i-1][j];for(i=0;i<10;i++)for(j=0;j<10;j++){if(i>=j)printf("%-4d",a[i][j]);if(j==9)putchar('\n');}putchar('\n');}int a[25][25]={0}; //魔方阵void array(int n){staticint b[2];inti,j,k;for(k=1;k<=n*n;k++){if(k==1){a[0][n/2]=k;b[0]=0;b[1]=n/2;}else{if(b[0]==0&&b[1]<n-1){a[n-1][(b[1]+1)]=k;b[0]=n-1;b[1]=b[1]+1;}else if(b[0]>0&&b[1]==n-1){a[b[0]-1][0]=k;b[0]=b[0]-1;b[1]=0;}else if(b[0]==0&&b[1]==n-1){a[1][n-1]=k;b[0]=1;b[1]=n-1;}else if(a[b[0]-1][b[1]+1]!=0){a[b[0]+1][b[1]]=k;b[0]=b[0]+1;}else{a[(b[0]-1)][(b[1]+1)]=k;b[0]=b[0]-1;b[1]=b[1]+1;}}}for(i=0;i<n;i++)for(j=0;j<n;j++){printf("%-5d",a[i][j]);if(j==n-1)putchar('\n');}}int main(){int n;printf("输入小于25的奇数:");scanf("%d",&n);array(n);}int main()int a[3][3],i,j,k,l,max; //寻找鞍点printf("输入矩阵:\n");for(i=0;i<3;i++)for(j=0;j<3;j++)scanf("%d",&a[i][j]);for(i=0;i<3;i++){max=a[i][0];l=0;for(j=1;j<3;j++){k=0;if(max<a[i][j]){max=a[i][j];l=j;}if(j==2){for(;k<3;k++)if(max<=a[k][l])continue;elsebreak;}if(k==3)printf("鞍点为:%d\n",max);}}}void star(){printf("* * * * *\n"); //打印图案}int main(){inti,j;for(i=0;i<5;i++){for(j=0;j<2*i;j++)printf(" ");star();}#define N 15voidnum(int a[],int n){int min=0,max=N-1,mid=N/2; //折半查找法while(min<=max){mid=(max+min)/2;if(n>a[mid]){min=mid+1;}else if(n<a[mid]){max=mid-1;}else{printf("第%d个数\n",mid+1);break;} }if(min>max)printf("无此数!\n");}int main(){int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},n,i;for(i=0;i<N;i++)printf("%-3d",a[i]);printf("\nenter number:");scanf("%d",&n);num(a,n);}int main(){char a[3][80],u=0,l=0,n=0,b=0,o=0,i,j;for(i=0;i<3;i++)for(j=0;j<80;j++)scanf("%c",&a[i][j]);for(i=0;i<3;i++)for(j=0;j<80;j++){if(a[i][j]>='A'&&a[i][j]<='Z')u+=1;else if(a[i][j]>='a'&&a[i][j]<='z')l+=1;else if(a[i][j]>='0'&&a[i][j]<='9')n+=1;else if(a[i][j]==' ')b+=1;elseo+=1;}printf("\n大写字母个数:%d\n小写字母个数:%d\n数字个数:%d\n空格个数:%d\n 其他字符个数:%d\n",u,l,n,b,o);}# define N 20int main(){char a[N]="512/R olevblf",b[N];inti=0,j=0;printf("密码:");while(a[i]){printf("%c",a[i]);i++;}printf("\n原文:");while(a[j]){if(a[j]>='a'&&a[j]<='z')b[j]='a'+'z'-a[j];else if(a[j]>='A'&&a[j]<='Z')b[j]='A'+'Z'-a[j];elseb[j]=a[j];j++;}b[j]='\0';printf("%s\n",b);}#define N 20void str_cat(char a[],char b[]) //字符串连接{int s1=strlen(a),i=0;while(b[i]){a[s1+i]=b[i];i++;}a[s1+i]='\0';}int main(){char a[N]="I ",b[N]="love you!";str_cat(a,b);printf("%s\n",a);}#define N 20void str_cpy(char a[],char b[]) //字符串复制{inti=0;while(a[i]=b[i])i++;}int main(){char s1[N],s2[]="I love you!";str_cpy(s1,s2);printf("s2=%s\ns1=%s\n",s2,s1);}*/#define N 20intstr_cmp(char a[],char b[]) //字符串比较{inti=0,n;n=strlen(b);while(a[i]==b[i]){i++;if(i==n)break;}printf("%d",a[i]-b[i]);}int main(){char s1[N],s2[N];gets(s1);gets(s2);str_cmp(s1,s2);putchar('\n');}。
C语言程序设计-第三版-谭浩强主编第6—8章课后习题答案
C语言程序设计-第三版-谭浩强主编第6—8章课后习题答案第六章循环语句6.1输入两个正数,求最大公约数和最小公倍数.#includevoidmain(){inta,b,num1,num2,temp;printf(\请输入两个正整数:\\n\canf(\if(num1temp=num1;num1=num2;num2=temp;}a=num1,b=num2;while(b!=0){temp=a%b;a=b;b=temp;}printf(\它们的最大公约数为:%d\\n\printf(\它们的最小公倍数为:%d\\n\}编译已通过6.2输入一行字符,分别统计出其中英文字母,空格,数字和其它字符的个数.解:#includevoidmain(){charc;intletter=0,pace=0,degit=0,other=0;printf(\请输入一行字符:\\n\while((c=getchar())!='\\n'){if(c>='a'&&c<='z'||c>'A'&&c<='Z')letter++;eleif(c=='')pace++;eleif(c>='0'&&c<='9')digit++;eleother++;}printf(\其中:字母数=%d空格数=%d数字数=%d其它字符数=%d\\n\digit,other);}6.3求(n)=a+aa+aaa++aaa之值,其中a是一个数字,n表示a的位数。
解:voidmain(){inta,n,count=1,n=0,tn=0;printf(\请输入a和n的值:\\n\canf(\printf(\while(count<=n){tn=tn+a;n=n+tn;a=a某10;++count;}printf(\\\n\}6.4求(即1+2!+3!+4!++20!)voidmain(){floatn,=0,t=1;for(n=1;n<=20;n++){t=t某n;=+t;}printf(\\\n\}阶乘利用递归,再求和:#includeuingnamepacetd;longFunc(intn){ if(1==n)returnn;if(n>1)returnn某Func(n-1);}main(){long=0;inti=1;while(i<=6){=+Func(i);i++;}cout<6.5求voidmain(){intk,N1=100,N2=50,N3=10;float1=0.0,2=0.0,3=0.0;for(k=1;k<=N1;k++)/某计算1到100的和某/{1=1+k;}for(k=1;k<=N2;k++)/某计算1到50各数平方和某/{2=2+k某k;}for(k=1;k<=N3;k++)/某计算1到10各数倒数之和某/{3=3+1.0/k;}printf(\总和=%8.2f\\n\}已通过intmain(){intk=1,i=11,j=51;float=0.0;while(k<=10){=+k+k某k+1.0/k;while(k==10&&i<=50){=+i+i某i;while(i=50&&j<=100){ =+j;j++;}i++;}k++;}}6.6所谓“水仙开数”是指一个3位数,其个位数字立方和等于该数本身。
C第六章习题答案(大题非选做).docx
6-3 (1)#include <iostream>using namespace std;int main(void){int num[10], *p, i, j, temp; cout«**输入10 个整数"vvendl; for(i=0; i<10; i++){ cin»num[订;}for(i=0; i<10; ■++){// 0, 1_________ 8p = &num[i];for(j = i+1; J<10; j++){//1, 2・.・ 9 if(num[i]<=num[J]){p = &num[j];}}cout«*p«endl; temp = *p;*p = num[i]; num[i] = temp;}system(M pause f,);return 0;(2)注:N的数值可以在宏定义中更改,以下是W12的吋候:#include <iostream>using namespace std;#define N 12struct N0DE{int num;NODE *next;};int i:class List{private:NODE list[N];NODE *temp;public:List() {//设置一个结点组成的圈temp = Iist;Iist[0].num = 1 ;Iist[0].next = &list[1];//第一个结点己经完成for(i=1: i<(N-1); ■++){Iist[i].num = i+1:Iist[i].next = &Iist[i+1];}//第二个至倒数第二个已经完成Iist[N-1].num = N;Iist[N-1].next = &list[O];//最后一个结点已经完成void Next2(){temp = temp->next;temp = temp->next;}void Fun(){temp = & list[N-1];//得到链表的最后一个结点地址do{Next2();//当前是0,数到2〃现在temp已经是标号为2的结点的地址了cout«(temp->next)->num«ff M;//$ny出要被删除的结点(p+1) temp->next = (temp->next)->next ;//^ 被删除的结点的前一个(p)和后一个相连接(p+2)}while(temp->next != (temp->next)->next); cout«temp->num;}};int main(void){List one; one.Fun(j; system(ft pause f,); return 0;}(3)#include <iostream>#include <string> using namespace std;#define SIZE 512class Str{private:char str1[SIZE]:char str2[SIZE];char *p;int i, length;public:void set(){cout«ff输入第一个字符串:ff«endl; cin>>str1;cout«ff输人第二个字符串:ft«endl; cin>>str2;}void fun(){Iian(str1, str2):}void Iian(char *m, char *n){ length = strlen(n); for(i=0; i<strlen(n)+1; i++){ P = & n[i];str1 [length+i] = *p;}cout«ft连接之后的结果:\n ft«str1«endl;}};int main(void){ Str one; one.set(); one.funO; system(ft pause f,); return 0;}(4)#include <iostream>#include <string>using namespace std;#define SIZE 512class Str{private:char str[SIZE]:int upper, lower, space, number, other, i:public:Str(){upper=Iower=space=number=other=0;void set(){cout«ff输入一个字符ff«endl;gets(str);}void check(){for(i=0; i<strlen(str); i++){if(str[i]>=w A・ && str[i]<="Z>){upper++;}else if(str[i]>=w a w && str[i]<=w z w){lower++;}else if(str[i]=="・){space++;}else if(str[i]>=w O w && str[i]<=w9w){number++;}else{other++;}}}void te11(){check();coutvv"箕冇大写字母ff«upper«ft个,小写字母"«lower«ff个,空格"vvspacevv”个,数字ff«numbervv”个,其他字符■•vvothervv”个”vvendl;}};int main(void){Str one;one.set();one.tel 1();system(ft pause ff);return 0;}(5)代码中要用到strlen函数,所以包含了string头文件,但strcmp函数在string中己经定义,所以下题屮改用Strcmpo#include <iostream>#include <string>using namespace std;#define SIZE 512class Str{private:char str1[SIZE];char str2[SIZE];■ nt i;public:void get(){cout«ft输入第一个字符串vvendl;OP+Q(Q+r1\■cout«M输入菊二个字符串:“vvendl; gets(str2);}void fun(){ Strcmp(str1, str2);}void Strcmp(char *m, char *n){int num;for(i=0; i<strlen(str1) || i<strlen(str2); i++){if(str1[i]==str2[i]){num = 0;}else{num = str1[i] - str2[i]; break;}}}};irrt main(void){Str one;one.get();one・fun();system(fl pause f,); return 0;}(6)注意:原有数组是不变的,但指针数组是排序Z后的。
《C语言程序设计》第6章习题答案
1、选择题(1)A(2)C(3)A(4)B(5)B(6)D(7)D(8)B(9)D(10)B2、填空题(1)a=10,b=20a=20,b=10(2)**pp=603、程序设计题(1)#include<stdio.h>char *month_name(int n);void main(){int n;printf("\nPlease enter 1 integer:");scanf("%d",&n);printf("%d month :%s\n",n,month_name(n));}char *month_name(int n){static char*name[]={"illegal month","Jan","Feb","Mar","Apr","May","Jun","July","Aug","Sept","Oct","Nov","Dec"};return ((n<1||n>12)?name[0]:name[n]);}(2)#include<stdio.h>#define N 10sort(int data[]){int i,j,min_a,temp;for(i=0;i<N;i++){min_a=i;for(j=i+1;j<N;j++)if(*(data+j)<*(data+min_a))min_a=j;if(min_a!=i){temp=*(data+min_a);*(data+min_a)=*(data+i);*(data+i)=temp;}}}main(){int i,j,data[N],temp;int min_a;printf("\nPlease input %d int:\n",N);for(i=0;i<N;i++)scanf("%d",&data[i]);sort(data);printf("After sorted:\n");for(i=0;i<N;i++)printf(" %d",data[i]);}(3)#include <stdlib.h>void reverse(char *c);void main(){char str[80];puts("Please enter 1 string\n");gets(str);reverse(str) ;puts("After reversed\n");puts(str);}void reverse(char *c){char *p,*q,temp;int size=0;for(p=c;*p!='\0';p++)size++;size=size/2;for(q=c,p--;q<c+size;q++,p--){temp=*q;*q=*p;*p=temp;}}(4)#include<stdio.h>#include<string.h>void sort(char *keyword[],int size);void print(char *keyword[],int size)void main(){char *keyword[]={"if","else","case","switch","do","whlie","for","break","continue"};sort(keyword,9);print(keyword,9);}void sort(char *keyword[],int size){int i,j,min_location;char *temp;for(i=0;i<size-1;i++){min_location=i;for(j=i+1;j<size;j++)if(strcmp(keyword[min_location],keyword[j])>0) min_location=j;if(min_location!=i){temp=keyword[i];keyword[i]=keyword[min_location];keyword[min_location]=temp;}}}void print(char *keyword[],int size){int i;for(i=0;i<size;i++)printf("\n%s",*(keyword+i));}(5)#include<stdio.h>void fun_char(char str1[],char str2[],char str3[]);void main(){char str1[80],str2[80],str3[80],c,i;printf("\nPlease enter 2 string:");scanf("%s%s",str1,str2);fun_char(str1,str2,str3);printf("Third string is %s.",str3);}void fun_char(char *str1,char *str2,char *str3){int i,j,k,flag;i=0,k=0;while(*(str1+i)!='\0'){j=0;flag=1;while(*(str2+j)!='\0'&&flag==1){if(*(str2+j)==*(str1+i)) flag=0;j++;}if(flag){*(str3+k)=*(str1+i); k++;}i++;}*(str3+k)='\0';}(6)#include<stdio.h>int count_word(char *str);void main(){char str1[80],c,res;puts("\nPlease enter a string:");gets(str1);printf("There are %d words in this sentence",count_word(str1)); }int count_word(char *str){int count ,flag;char *p;count=0;flag=0;p=str;while(*p!='\0'){if(*p==' ')flag=0;else if(flag==0){flag=1;count++;}p++;}return count;}(7)#include<stdio.h>#include<string.h>char *encrypt(char *string);char *decrypt(char *string);main(){char item[80];char *point;char *pEncrypted;char *pDecrype;printf("Please enter the string need to encrypt:\n");gets(item);point=item;pEncrypted=encrypt(point);printf("\nThe string after encrypted is:\n%s\n",pEncrypted); pDecrype=decrypt(pEncrypted);printf("\nThe string after decrypted is:\n%s\n",pDecrype);free(pEncrypted);free(pDecrype);}char *encrypt(char *string){char *q,*t;q=(char *)malloc(sizeof(char)*80);if(!q){printf("No place to malloc!");return 0;}t=q;while(*string!='\0'){*q=*string-2;string++;q++;}*q='\0';return t;}char *decrypt(char *string){char *q,*t;q=(char *)malloc(sizeof(char)*80); if(!q){printf("No place to malloc!");return 0;}t=q;while(*string!='\0'){*q=*string+2;string++;q++;}*q='\0';return t;}。
c语言程序设计第五版课后答案谭浩强第六章习题答案
c语⾔程序设计第五版课后答案谭浩强第六章习题答案第六章:利⽤数组处理批量数据1. ⽤筛选法求100之内的素数【答案解析】素数:约数为1和该数本⾝的数字称为素数,即质数筛选法:⼜称为筛法。
先把N个⾃然数按次序排列起来。
1不是质数,也不是合数,要划去。
第⼆个数2是质数留下来,⽽把2后⾯所有能被2整除的数都划去。
2后⾯第⼀个没划去的数是3,把3留下,再把3后⾯所有能被3整除的数都划去。
3后⾯第⼀个没划去的数是5,把5留下,再把5后⾯所有能被5整除的数都划去。
这样⼀直做下去,就会把不超过N 的全部合数都筛掉,留下的就是不超过N的全部质数。
因为希腊⼈是把数写在涂腊的板上,每要划去⼀个数,就在上⾯记以⼩点,寻求质数的⼯作完毕后,这许多⼩点就像⼀个筛⼦,所以就把埃拉托斯特尼的⽅法叫做“埃拉托斯特尼筛”,简称“筛法”。
(另⼀种解释是当时的数写在纸草上,每要划去⼀个数,就把这个数挖去,寻求质数的⼯作完毕后,这许多⼩洞就像⼀个筛⼦。
)【代码实现】//⽤筛选法求100以内的素数#include<stdio.h>int main(){int i, j, k = 0;// 将数组汇总每个元素设置为:1~100int a[100];for (i = 0; i < 100; i++)a[i] = i+1;// 因为1不是素数,把a[0]⽤0标记// 最后⼀个位置数字是100,100不是素数,因此循环可以少循环⼀次a[0] = 0;for (i = 0; i < 99; i++){// ⽤a[i]位置的数字去模i位置之后的所有数据// 如果能够整除则⼀定不是素数,该位置数据⽤0填充for (j = i + 1; j < 100; j++){if (a[i] != 0 && a[j] != 0){//把不是素数的都赋值为0if (a[j] % a[i] == 0)a[j] = 0;}}}printf(" 筛选法求出100以内的素数为:\n");for (i = 0; i < 100; i++){//数组中不为0的数即为素数if (a[i] != 0)printf("%3d", a[i]);}printf("\n");return 0;}【运⾏结果】2. ⽤选择法对10个整数排序【答案解析】选择排序原理:总共两个循环,外循环控制选择的趟数,内循环控制具体选择的⽅式。
C++程序设计基础课后答案第六章
C++程序设计基础课后答案第六章6.1 阅读下列程序,写出执行结果1. #includeclass T{ public :T() { a = 0; b = 0; c = 0; }T( int i , int j , int k ){ a = i; b =j ; c = k; }void get( int &i , int &j , int &k ) { i = a; j = b; k = c; }T operator * ( T obj );private:int a , b , c;};T T::operator * ( T obj ){ T tempobj;tempobj.a = a * obj.a;tempobj.b = b * obj.b;tempobj.c = c * obj.c;return tempobj;}void main(){ T obj1( 1,2,3 ), obj2( 5,5,5 ), obj3; int a , b , c;obj3 = obj1 * obj2;obj3.get( a, b, c );cout << "( obj1 * obj2 ): \t"<< "a = " << a << '\t' << "b = " << b<< '\t' << "c = " << c << '\t' << endl; ( obj2 * obj3 ).get( a, b, c );cout << "( obj2 * obj3 ): \t "<< "a = " << a << '\t' << "b = " << b << '\t' << "c = "<< c<< '\t' << endl; }2. #include < iostream.h >class Vector{ public:Vector(){ }Vector(int i,int j){ x = i ; y = j ; }friend Vector operator + ( Vector v1, Vector v2 ){ Vector tempVector ;tempVector.x = v1.x + v2.x ;tempVector.y = v1.y + v2.y ;return tempVector ;}void display(){ cout << "( " << x << ", " << y << ") "<< endl ; } private:int x , y ;};void main(){ Vector v1( 1, 2 ), v2( 3, 4 ), v3 ;cout << "v1 = " ;v1.display() ;cout << "v2 = " ;v2.display() ;v3 = v1 + v2 ;cout << "v3 = v1 + v2 = " ;v3.display() ;}6.2 思考题1.一个运算符重载函数被定义为成员函数或友员函数,从定义方式、解释方式和调用方式上有何区别?可能会出现什么问题?请用一个实例说明之。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
第六章模板与数据结构习题一、.基本概念与基础知识自测题6.1 填充题6.1.1 模板是为了实现代码的(1),它把数据类型改为一个(2),称为(3)程序设计。
模板包括(4)和(5)。
答案:(1)重用(2)设计参数(3)参数化(parameterize)(4)函数模板(function template)(5)类模板(class template)6.1.2 调用函数模板时,可以显式指定模板参数类型,也可以隐式进行,称为(1),这是根据(2)来决定的。
答案:(1)模板实参推演(template argument deduction)(2)一组实际类型或(和)值6.1.3 顺序查找可以用于(1)线性表,而对半查找可以用于(2)线性表。
答案:(1)无序的(所有)(2)有序的6.1.4 最常见的排序方式有(1)、(2)和(3)。
如果现有一个已排好序的线性表,在表尾添加了一个元素,采用(4)排序法使它重新成为有序的所需工作量最小。
答案:(1)选择(2)插入(3)交换(4)交换(可利用原来的有序性)6.1.5 给出以下指针的说明方式:指向一个4元素整型数组的指针为(1);指向一个返回整型数,参数为两个整型数的函数的指针(2);指向一个数组的指针,而该数组元素都是指向一个返回整型指针的无参函数(3)。
答案:(1)int(*p)[4](2)int(*p)(int,int)(3)以指向6元素数组为例:int*(*)() (*p)[6]6.2简答题6.2.1需要编写一个对多维数组通用的算法(即各维的大小未定),怎样才能把实参多维数组的信息全部传递到函数中去?答:最佳方法是用函数模板,多维数组用模板类型参数传递,各维的大小作为参数传递。
也可以用一维数组加各维的大小都作为参数传递。
6.2.2什么叫函数模板?什么叫模板函数?什么叫类模板?什么叫模板类?答:不受数据类型限制的通用型的函数使代码的可重用性大大提高。
把数据类型改为一个设计参数是一个可行的方案。
这种程序设计类型称为参数化(Parameterize) 程序设计。
这样的软件模块由模板(Template) 构造。
包括函数模板和类模板。
函数模板定义如下:template<模板参数表> 返回类型函数名(形式参数表){……;//函数体}模板参数主要是模板类型参数。
模板类型参数代表一种潜在的内置或用户定义的类型,由关键字typename或class后加一个标识符构成。
函数模板可以用来创建一个通用功能的函数,以支持多种不同形参,简化重载函数的设计。
由调用函数模板(functron template) 而生成的函数,称为模板函数(template function)。
类模板定义如下:template<模板参数表> class类名{……;//类声明体};模板参数有两种:模板类型参数和模板非类型参数。
模板类型参数(template type parameter),它代表一种类型,由关键字typename或class后加一个标识符。
模板非类型参数由一个普通的参数声明构成。
模板非类型参数表示该参数名代表了一个潜在的常量。
如数组类模板,可以有一个数组长度的非类型参数。
为通用的类模板定义中的模板类型参数指定了具体类型而生成的类称为模板类。
6.2.3什么叫线性表?其基本操作包括哪些?其中插入一个元素的关键在哪儿?答:线性表是数据结构中的概念:每两个相邻元素之间都有直接前驱和直接后继的关系。
这里除第一个元素外,其他元素有且仅有一个直接前驱,第一个元素没有前驱;除最后一个元素外,其他元素有且仅有一个直接后继,最后一个元素无后继。
这样的特性称为线性关系。
基本操作包括:计算表长度,寻找变量或对象x(其类型与表元素相同)在表中的位置(下标值),判断x是否在表中,删除x,将x插入列表中第i个位置,寻找x的后继,寻找x的前驱,判断表是否空,判断表是否满,取第i个元素的值等。
当需要在顺序表的指定位置i插入一个数据x时,必须为它腾出这个位置,把从该位置开始向后的所有元素数据,后移一个位置,最后才插入。
关键是后移时从最后一个元素开始。
否则先移的数据会冲掉未移的数据。
6.2.4采用索引查找有哪些优点?它需要被查找数据有序吗?答:索引,就象一本书的目录,找到标题,再看一下页号,立即可以翻到。
索引查找不要求被查找数据有序,只要求索引有序。
6.2.5简单叙述阅读理解复杂指针的方法。
设Node为类,下面两个标识符fa和pa分别代表什么?Node* (*fa(int))(); Node* (*(*pa)[])();答:理解和构造对象说明的方法是:先撇开标识符,按从右到左的顺序逐个解释每个说明符,如果有括号则改变解释的先后,先解释括号内再解释括号外。
fa是有一个整型参数的函数,其返回值是指针,该指针是指向无参函数的指针,而该无参函数的返回值是指向Node类的指针。
pa是指向数组的指针,该数组的元素均为函数指针,所指向的函数无参、返回值是指向Node类的指针。
二、.编程与综合练习题6.3 使用自定义字符串类,编写求数组元素中最大值的函数模板。
解:函数模板有三种应用方式:1.类模板的成员函数,在模板类型参数中重载函数和运算符,直接访问私有数据成员,实现通用算法。
这是标准的面向对象的方法。
2.函数模板处理模板类,以类模版为参数,用模板类型参数中重载的函数或运算符,实现通用算法。
但调用类模板的接口函数间接访问私有数据成员,也是常见的。
3.函数模板处理普通数据,往往要用函数作为参数,实现通用算法。
这是面向过程的方法。
解:使用独立的函数模板,相对简单。
#include<iostream>using namespace std;const int n=256;class mystring{//为简单只保留用到的函数char str[n]; //存放字符串的数组容器int maxsize; //最大可用元素数,可防止数组出界,提高健壮性int last; //已用元素数public:mystring(){last=-1;maxsize=n;str[0]='\0';cout<<"缺省构造函数"<<endl;}mystring(char *s){//当C字符串过长,初始化时采用截尾处理last=-1;maxsize=n;do{last++;str[last]=s[last];}while(s[last]!='\0'&&last<maxsize-1);str[last] ='\0'; //截尾处理时,必须加串结束符cout<<"构造函数"<<endl;}mystring(mystring & ms){last=-1;maxsize=n;do{last++;str[last]=ms.str[last];}while(last<st);cout<<"拷贝构造函数"<<endl;}~mystring(){cout<<"析构函数"<<endl;}void show(){//如需重载<<,则请参见9.3节,暂时未学到,替代方法是改用show()函数cout<<str<<endl;}mystring & operator=(char * ms);//这里重载的=是把C风格字符串赋给mystringmystring& operator=(mystring &);bool operator<(mystring &);};mystring & mystring::operator=(char* ms){ //用C字符串赋值自定义字符串last=-1;do{last++;str[last]=ms[last];}while(ms[last]!='\0'&&last<maxsize-1);str[last] ='\0'; //截尾处理时,必须加串结束符return *this;}//这里返回值为引用,不调用拷贝构造函数mystring& mystring::operator=(mystring & ms){last=-1;do{last++;str[last]=ms.str[last];}while(last<st);cout<<"赋值函数"<<endl;return *this;}bool mystring::operator<(mystring & ms){int i=0,k;do{k=str[i]-ms.str[i];i++;}while(k==0&&i<last&&i<st);if(k<0) return true;if(i==last&&i!=st) return true;return false;}template <typename Groap>Groap max(Groap *r_array,int size){//这里是一个独立的函数模板Groap max_val=r_array[0];for (int i=1;i<size; ++i) if(max_val<r_array[i]) max_val=r_array[i];return max_val;}int main(){int i;char sp[6][10]={"南京大学","东南大学","交通大学","清华大学","天津大学","复旦大学"};mystring ms[6];// 对象数组for(i=0;i<6;i++) ms[i]=sp[i];cout<<"打印学校名称:"<<endl;for(i=0;i<6;i++) ms[i].show();cout<<"按字典序查找校名:"<<endl;(max<mystring>(ms,6)).show();return 0;}6.4 将自定义字符串类用于对半查找的函数模板。
解1:为简化,使用独立的函数模板#include<iostream>using namespace std;const int n=256;class mystring{//为简单只保留用到的函数char str[n]; //存放字符串的数组容器int maxsize; //最大可用元素数,可防止数组出界,提高健壮性int last; //已用元素数public:mystring(){last=-1;maxsize=n;str[0]='\0';cout<<"缺省构造函数"<<endl;}mystring(char *s){//当C字符串过长,初始化时采用截尾处理last=-1;maxsize=n;do{last++;str[last]=s[last];}while(s[last]!='\0'&&last<maxsize-1);str[last] ='\0'; //截尾处理时,必须加串结束符cout<<"构造函数"<<endl;}mystring(mystring & ms){last=-1;maxsize=n;do{last++;str[last]=ms.str[last];}while(last<st);cout<<"拷贝构造函数"<<endl;}~mystring(){cout<<"析构函数"<<endl;}void show(){//如需重载<<,则请参见9.3节,暂时未学到,替代方法是改用show()函数cout<<str<<endl;}mystring & operator=(char * ms);//这里重载的=是把C风格字符串赋给mystringmystring& operator=(mystring &);bool operator<(mystring &);};mystring & mystring::operator=(char* ms){ //用C字符串赋值自定义字符串last=-1;do{last++;str[last]=ms[last];}while(ms[last]!='\0'&&last<maxsize-1);str[last] ='\0'; //截尾处理时,必须加串结束符return *this;}//这里返回值为引用,不调用拷贝构造函数mystring& mystring::operator=(mystring & ms){last=-1;do{last++;str[last]=ms.str[last];}while(last<st);cout<<"赋值函数"<<endl;return *this;}bool mystring::operator<(mystring & ms){int i=0,k;do{k=str[i]-ms.str[i];i++;}while(k==0&&i<last&&i<st);if(k<0) return true;if(i==last&&i!=st) return true;return false;}template <typename T> int BinarySearch(T *array,T & x,int size){//独立的函数模板int high=size-1 ,low=0,mid; // size 当前有序表元素数量while(low<=high){mid=(low+high)/2;if(x<array[mid]) high=mid-1; //左缩查找区间,这里只有重载的小于号else if(array[mid]<x) low=mid+1;// 右缩查找区间else return mid;}return mid;}int main(){//此例为了简化未用对象数组类模板int i;char sp[6][10]={"东南大学","复旦大学","交通大学","南京大学","清华大学","天津大学"};mystring ms[6],x="交通大学",y="南京大学";for(i=0;i<6;i++) ms[i]=sp[i];for(i=0;i<6;i++) ms[i].show();i=BinarySearch(ms,x,6);cout<<i<<endl;i=BinarySearch(ms,y,6);cout<<i<<endl;return 0;}解2:函数模板使用成员函数(ep6_4_0.cpp)#include<iostream>using namespace std;const int n=256;class mystring{//为简单只保留用到的函数char str[n]; //存放字符串的数组容器int maxsize; //最大可用元素数,可防止数组出界,提高健壮性int last; //已用元素数public:mystring(){last=-1;maxsize=n;str[0]='\0';cout<<"缺省构造函数"<<endl;}mystring(char *s){//当C字符串过长,初始化时采用截尾处理last=-1;maxsize=n;do{last++;str[last]=s[last];}while(s[last]!='\0'&&last<maxsize-1);str[last] ='\0'; //截尾处理时,必须加串结束符cout<<"构造函数"<<endl;}mystring(mystring & ms){last=-1;maxsize=n;do{last++;str[last]=ms.str[last];}while(last<st);cout<<"拷贝构造函数"<<endl;}~mystring(){cout<<"析构函数"<<endl;}void show(){//如需重载<<,则请参见9.3节,暂时未学到,替代方法是改用show()函数cout<<str;}mystring & operator=(char * ms);//这里重载的=是把C风格字符串赋给mystringmystring& operator=(mystring &);bool operator<(mystring &);};mystring & mystring::operator=(char* ms){ //用C字符串赋值自定义字符串last=-1;do{last++;str[last]=ms[last];}while(ms[last]!='\0'&&last<maxsize-1);str[last] ='\0'; //截尾处理时,必须加串结束符return *this;}//这里返回值为引用,不调用拷贝构造函数mystring& mystring::operator=(mystring & ms){last=-1;do{last++;str[last]=ms.str[last];}while(last<st);cout<<"赋值函数"<<endl;return *this;}bool mystring::operator<(mystring & ms){int i=0,k;do{k=str[i]-ms.str[i];i++;}while(k==0&&i<last&&i<st);if(k<0) return true;if(i==last&&i!=st) return true;return false;}template <typename T,int size>class Orderedlist{int maxsize;int last;T slist[size];public:int getlast(){return last;}T getslist(int k){return slist[k];}void putslist(T t,int k){slist[k]=t;}Orderedlist(){last=-1;maxsize=size;}bool Insert(T & elem,int i);void print();int BinarySearch(T);// 无关成员函数省略,缺省的=等不必定义};//再次指出分号不可少template <typename T,int size> bool Orderedlist<T,size>::Insert(T & elem ,int i){ if (i<0||i>last+1||last==maxsize-1) return false;else{last++;for (int j=last;j>i;j--) slist[j]=slist[j-1];slist[i]=elem;return true;}}template <typename T,int size> void Orderedlist<T,size>::print(){int i;for(i=0;i<=last;i++){slist[i].show();if(i%5==4) cout<<endl; //打印5个名称换行else cout<<'\t';}cout<<endl;}template <typename T,int size> int Orderedlist<T,size>::BinarySearch(T x){//成员函数模板int high=last,low=0,mid; //size当前有序表元素数量while(low<=high){mid=(low+high)/2;if(x<slist[mid]) high=mid-1; //左缩查找区间,这里只有重载的小于号else if(slist[mid]<x) low=mid+1;// 右缩查找区间else return mid;}return mid;}int main(){const int h=8;int i;Orderedlist<mystring,h> ordlist;mystring n[h];char sp[h][10]={"东南大学","复旦大学","交通大学","南京大学","清华大学", "天津大学","同济大学","浙江大学"};for(i=0;i<h;i++) n[i]=sp[i];for(i=0;i<h;i++) ordlist.Insert(n[i],i); //建立顺序表cout<<"排序表:"<<endl;ordlist.print();mystring x("交通大学"),y("东南大学");i=ordlist.BinarySearch(x);cout<<i<<endl;i=ordlist.BinarySearch(y);cout<<i<<endl;return 0;}6.5 编一个冒泡排序的成员函数模板实现降序排序。