C语言程序设计第六章课后习题
- 格式:ppt
- 大小:130.00 KB
- 文档页数:6
第六章课后习题答案(第二版谭浩强)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;}(学习的目的是增长知识,提高能力,相信一分耕耘一分收获,努力就一定可以获得应有的回报)。
实验六数组练习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,循环。
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语言程序设计第四版第六章答案_谭浩强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语言程序设计– 第六章课后习题电子13-02班王双喜一、选择题1. C语言中一维数组的定义方式为:类型说明符数组名(C)A. [整型常量]B. [整型表达式]C. [整型常量]或[整型常量表达式]D. [常量表达式]2. C语言中引用数组元素时,下标表达式的类型为(C)A. 单精度型B. 双精度型C. 整型D. 指针型3. 若有定义:int a[3][4];,则对a数组元素的非法引用是(D)A. a[0][3*1]B. a[2][3]C. a[1+1][0]D. a[0][4](解释:A、B、C均正确,D看起来引用不太妥当,但其亦有其意义(a[0][4]等价于a[1][0]))4. 若有定义:int a[][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};,则a数组的第一维大小是(C)A. 1B. 2C. 3D. 4(解释:共9个元素,除以3即可得第一维大小是3;若有余数,则应加1)5. 若有定义:int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};,则值为5的表达式是(C)A. a[5]B. a[a[4]]C. a[a[3]]D. a[a[5]]6. 要求定义包含8个int类型元素的一维数组,以下错误的定义语句是(A)A. int N = 8;int a[N]; B. #define N 3while (a[2*N+2];C. int a[] = {0, 1, 2, 3, 4, 5, 6, 7};D. int a[1+7] = {0};(解释:数组的大小必须是整型常量或整型常量表达式)7. 若二维数组a有m列,则在a[i][j]前的元素个数为(A)A. i * m + jB. j * m + iC. i * m + i - 1D. i * m + j - 18. 下面是对数组s的初始化,其中不正确的是(D)A. char s[5] = {"abc"};B. char s[5] = {'a', 'b', 'c'};C. char s[5] = "";D. char s[5] = "abcdef";(解释:D中元素个数太多,算上'\0'共六个,非法)9. 下面程序段的运行结果是(B)char c[] = "\t\v\\\0will\n";printf("%d", strlen(c));A. 14B. 3C. 9D. 字符串中有非法字符,输出值不确定(解释:字符串中第四个是'\0'即结束标志,因此字符串长度是3)10. 判断字符串s1是否等于s2,应当使用(D)A. if (s1 == s2)B. if (s1 = s2)C. if (strcpy(s1, s2))D. if (strcmp(s1, s2) == 0)(解释:对于字符串来讲,其名字的内容是该字符串的起始地址,不能通过比较名字来比较相等,而应该用专用的函数进行逐字符匹配)二、写出程序的执行结果1. 程序一:# include <stdio.h>main(){int a[3][3] = {1, 3, 5, 7, 9, 11, 13, 15, 17};int sum = 0, i, j;for (i = 0; i < 3; i++)for (j = 0; j < 3; j++){a[i][j] = i + j;if (i == j) sum = sum + a[i][j];}printf("sum = %d", sum);}执行结果:打印sum = 6.(解释:a中各个元素的值是其行和列数字之和,sum内保存a中对角线元素之和,即sum = 0 + 2 + 4)2. 程序二:# include <stdio.h>main(){int i, j, row, col, max;int a[3][4] = {{1, 2, 3, 4}, {9, 8, 7, 6}, {-1, -2, 0, 5}};max = a[0][0]; row = 0; col = 0;for (i = 0; i < 3; i++)for (j = 0; j < 4; j++)if (a[i][j] > max){max = a[i][j];row = i;col = j;}printf("max = %d, row = %d, col = %d\n", max, row, col);}执行结果:打印max = 9, row = 1, col = 0.(解释:此程序的功能是逐行逐列扫描元素,总是将最大的元素赋给max,并保存该元素的行数和列数;因此执行完毕后,max是最大的元素(9),row是其行数(1),col是其列数(0))3. 程序三:# include <stdio.h>main(){int a[4][4], i, j, k;for (i = 0; i < 4; i++)for (j = 0; j < 4; j++)a[i][j] = i - j;for (i = 0; i < 4; i++){for (j = 0; j <= i; j++)printf("%4d", a[i][j]);printf("\n");}}执行结果:第一行打印0;第二行打印1 0;第三行打印2 1 0;第四行打印3 2 1 0。
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语⾔程序设计教程第六章课后习题参考答案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);}}。
第6章练习与思考1.指针变量有哪几种运算类型?除了一般变量能做的它都能做以外,还有取地址和取内容运算。
2.有一个4x4的矩阵,试用指针变量按照4行4列格式,输岀矩阵中各元素的值。
#include "stdio.h"void main(){int 询4][4]={{1,1丄1},{1丄1,1},{1丄1,1},{1,1,1,1}};int *p=a;for(i=0;i<4*4;i++){ printf(n%3d",*(p+i));if((i+l)%4=0)printf(H\n H);}}3•输出一个字符串,将这个字符串屮大写字母改为小写字母,第一个字母变大写。
#include "stdio.h"void main(){char a[100],*p 二NULL;int i;printf(n Please input a string:\n H);gets(a);P=a;if(*p>=,a,&&*p<=,z,)*p=*p・32;for(i=l;a[i]!='\O f;i++){if(*(p+i)>='A '&&*(p+i)v=Z) *(p+i)=*(p+i)+32;}puts(a);}4.指向函数的指针有哪些特点?(1)可以通过调用指向函数的指针来调用函数。
(2)对于已定义的函数指针可以指向返回值类型相同的不同函数。
(3)函数指针可做函数的参数。
5.编写程序,在己知字符串str中截取一子串。
要求该子串是从血的第m个字符开始, 由n个字符组成。
#include "stdio.h"void main()char str[100],s[100];char *pl=str,*p2=s;int i,m,n;printf(n please input string:\n");scanf(n%s n,str);printf(”please input m,n:\n n);scanf("%d,%d",&m,&n);for(i=0;i<n;i++)*(p2+i)=*(pl+m+i);for(i=0;*(p2+i)U\0:i++) prin(f(”%c”,*(p2+i));}6.编写程序,利用指针将二维数组屮各元素输出。
# 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语言程序设计教程1-6章习题汇总如果您在此文档中发现错误请您及时提出,我会以超光速为您解决!!!欢迎您提出宝贵意见!!!都是自己人编的,编的不是太好,凑活凑活用吧·······习题11.一个c语言程序是由若干个函数构成的,其中有且只能有一个(主)函数。
//这个大家都知道了,想想咱谭老师定义的2个主函数(一个忘了删),结果1个错误···所以嘛,若干函数只能有一个主函数···2.模仿求圆面积的算法,写出求圆周长的算法,用流图表示此算法。
答:第一步,我们要求圆周长,必先知道半径,而半径需要我们定义,即要求人工输入半径的值。
第二步,我们要知道圆周长的求解公式,应该没有不知道的吧··(l=2*∏*r)第三步,我们要输出l的值,第四步,完了···流程图为:(不太准确Word技巧有待改进···)3.编辑并运行下列程序,记录运行结果。
(1)#include<stdio.h>void main(){printf("welcome you\n");printf("*****************\n");}结果很简单:welcome you*******************(2)#include<stdio.h>void main(){int a,b,s;printf("please input two numbers:"); // 原样输出scanf("%d,%d",&a,&b); //输入a,b的值 s=a+b; //运算printf("s=%d\n",s); //输出}屏幕上为:please input three numbers:3,4s=7(3和4之间要加逗号,不要空格。
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位数,其个位数字立方和等于该数本身。
第六章指针一、选择题1 答案:A分析:本题主要考指针赋值,n2=n1;是把n2的值赋给n1,故根据指针赋值的定义可知选A,即把q所指对象的值赋给p所指对象。
2 答案:B分析:本题主要考指针定义,因为p指向变量x,故输出其值的时候应该是x的值。
3 答案:C分析:本题主要考指针的定义和赋值,C前面是定义一个量a并赋值为10,后面定义一个指针,并把a的值赋给这个指针。
4 答案:C分析:本题主要考指针的定义及赋值,开始时使p指向a,q指向b,把它们的值交换,然后再显示。
故得正确答案C。
5 答案:C分析:本题主要考函数指针的定义,函数前面的*号表求返回值是指针类型,void表示返回无值弄的。
故选C。
6 答案:A分析:本题主要考的是指针的变量的赋值,在使用scanf()函数的时候,后面跟的是一个地址,由于pa本身保存的是地址,故选A7 答案:D分析:本题主要考的指针的赋值及指向指针的指针的赋值,根据定义知选D。
B的正确形式是**q=2;C的正确形式应该是q=&p。
8 答案:C分析:本题主要考的是全局变量和局部变量,以及指针的用法,第一个f(&a)的返回值是5,第二个返回值是2。
9 答案:A分析:本题主要考的是变量自加,指针传值,以及指针的赋值。
通过第二行a=b可知p1,p2指向的变量的值相同,都指向了b所指的对象,也是p2所指的对象’a’,由于(*a)++;是实现a所指对象的自加,故由’a’变成’b’,故最终选A。
10 答案:A分析:本题主考NULL,一般来说当我们把一个空值以整数的形式输出出来的时候,默认的情况是0。
11 答案:C分析:本题考的是指针变量的赋值,虽然p没有赋值,表示没有指向某个具体的对象,但事实上系统会让它随机的指向存储单元里的一个对象,那么它的返回值应该是所指存储单元中的值。
12 答案:B分析:本题主要考函数中参数变量的定义,在B中连续定义两个变量,这在函数中是不可以的。
Exercise6_2#include <iostream>using namespace std;int main(){// Prompt the user to enter the first numbercout << "Enter an integer: ";int max;cin >> max;int count = 1;// Prompt the user to enter the remaining five numbers for (int i = 1; i <= 5; i++) {cout << "Enter an integer: ";int temp;cin >> temp;if (temp > max) {max = temp;count = 1;}else if (temp == max)count++;}cout << "\n" <<"max is " << max << "\n" <<"the occurrence count is " << count;return 0;}Exercise6_4#include <iostream>using namespace std;int main(){double scores[100];double sum = 0;int count = 0;do{cout << "Enter a new score: ";cin >> scores[count];sum += scores[count];}while (scores[count++] >= 0);double average = (sum - scores[count]) / (count - 1);int numOfAbove = 0;int numOfBelow = 0;for (int i = 0; i < count - 1; i++)if (scores[i] >= average)numOfAbove++;elsenumOfBelow++;cout << "Average is " << average << endl;cout << "Number of scores above or equal to the average " << numOfAbove << endl; cout << "Number of scores below the average " << numOfBelow << endl;return 0;}Exercise6_6#include <iostream>#include <cmath>using namespace std;int main(){const int NUM_OF_PRIMES = 50;// Store prime numbersint primeNumbers[NUM_OF_PRIMES];int count = 0; // Count the number of prime numbersint number = 2; // A number to be tested for primenessbool isPrime = true; // Is the current number prime?cout << "The first 50 prime numbers are \n";// Repeatedly find prime numberswhile (count < NUM_OF_PRIMES){// Assume the number is primeisPrime = true;// Test if number is primefor (int i = 0; i < count && primeNumbers[i] <= sqrt(1.0 * number); i++) {//If true, the number is not primeif (number % primeNumbers[i] == 0){// Set isPrime to false, if the number is not primeisPrime = false;break; // Exit the for loop}}// Print the prime number and increase the countif (isPrime){primeNumbers[count] = number;count++; // Increase the countif (count % 10 == 0){// Print the number and advance to the new linecout << number << endl;}elsecout << number << "\t";}// Check if the next number is primenumber++;}return 0;}Exercise6_8#include <iostream>#include <cmath>using namespace std;int average(int array[], int size) {int sum = 0;for (int i = 0; i < size; i++)sum += array[i];return sum / size;}double average(double array[], int size) { double sum = 0;for (int i = 0; i < size; i++)sum += array[i];return sum / size;}int main(){int list1[] = {1, 2, 3, 4, 5, 6};double list2[] = {5.0, 4.4, 1.9, 2.9, 3.4, 3.5};cout << average(list1, 6) << endl;cout << average(list2, 6) << endl;return 0;}Exercise6_10#include <iostream>#include <cmath>using namespace std;int minIndex(int list[], int size){int min = list[0];int minIndex = 0;for (int i = 1; i < size; i++)if (min > list[i]){min = list[i];minIndex = i;}return minIndex;}int main(){int list[] ={1, 2, 4, 5, 10, 100, 2, -22};cout << "The index of the min is " << minIndex(list, 8) << endl;return 0;}Exercise6_12#include <iostream>using namespace std;void reverse(int list[], int size){for (int i = 0, j = size - 1; i < size / 2; i++, j--){int temp = list[i];list[i] = list[j];list[j] = temp;}}int main(){int myList[] ={1, 2, 3, 4, 5, 6, 7, 8};reverse(myList, 8);for (int i = 0; i < 8; i++)cout << myList[i] << " ";return 0;}Exercise6_14#include <iostream>#include "LinearSearch.h"#include "BinarySearch.h"#include "SelectionSort.h"using namespace std;int main(){int list[100000];for (int i = 0; i < 100000; i++){list[i] = rand();}int key = rand();long startTime = time(0);cout << linearSearch(list, key, 100000) << endl;long endTime = time(0);cout << "End time: " << endTime << endl;cout << "Start time: " << startTime << endl;long executionTime = endTime - startTime;cout << "Execution time for linear search is " << executionTime << endl; selectionSort(list, 100000);startTime = time(0);cout << binarySearch(list, key, 100000) << endl;endTime = time(0);executionTime = endTime - startTime;cout << "Execution time for binary search is " << executionTime << endl;return 0;}Exercise6_16#include <iostream>#include "LinearSearch.h"#include "BinarySearch.h"#include "SelectionSort.h"using namespace std;/** The method for printing numbers */void printList(double list[], int size){for (int i = 0; i < size; i++)cout << list[i] << " ";cout << endl;}void bubbleSort(double list[], int size) {bool changed = true;do{changed = false;for (int j = 0; j < size - 1; j++)if (list[j] > list[j + 1]){//swap list[j] wiht list[j+1]double temp = list[j];list[j] = list[j + 1];list[j + 1] = temp;changed = true;}}while (changed);}int main(){// Initialize the listdouble myList[] ={5.0, 4.4, 1.9, 2.9, 3.4, 3.5};// Print the original listcout << "My list before sort is: "; printList(myList, 6);// Sort the listbubbleSort(myList, 6);// Print the sorted listcout << "\nMy list after sort is: " << endl; printList(myList, 6);return 0;}Exercise6_18#include <iostream>using namespace std;int main(){int m[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; i < 4; i++)sum += m[i] [i];cout << "Sum of diagonal is " << sum << endl;return 0;}Exercise6_20#include <iostream>using namespace std;/** The method for sorting the numbers */void sortAndKeepIndex(int list[], int indexList[], int size) { int currentMax;int currentMaxIndex;// Initialize indexListfor (int i = 0; i < size; i++)indexList[i] = i;for (int i = size - 1; i >= 1; i--) {// Find the maximum in the list[0..i]currentMax = list[i];currentMaxIndex = i;for (int j = i - 1; j >= 0; j--) {if (currentMax < list[j]) {currentMax = list[j];currentMaxIndex = j;}}// Swap list[i] with list[currentMaxIndex] if necessary;if (currentMaxIndex != i) {list[currentMaxIndex] = list[i];list[i] = currentMax;// Swap the index in indexList tooint temp = indexList[i];indexList[i] = indexList[currentMaxIndex];indexList[currentMaxIndex] = temp;}}}int main(){const int NUMBER_OF_WORKERS = 8;double workHours[NUMBER_OF_WORKERS][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}};// Create an array to store total weekly hoursint weeklyHours[NUMBER_OF_WORKERS] = {0, 0, 0, 0, 0, 0, 0, 0};for (int i = 0; i < NUMBER_OF_WORKERS; i++)for (int j = 0; j < 7; j++)weeklyHours[i] += workHours[i][j];int indexList[NUMBER_OF_WORKERS];// Sort weeklyHourssortAndKeepIndex(weeklyHours, indexList, NUMBER_OF_WORKERS);// Display resultfor (int i = NUMBER_OF_WORKERS - 1; i >= 0; i--)cout << "Employee " << indexList[i] << ": " <<weeklyHours[i] << endl;return 0;}Exercise6_22#include <iostream>using namespace std;const int COLUMN_SIZE = 5;/** The method for multiplying two matrices */void multiplyMatrix(int a[] [COLUMN_SIZE], int b[] [COLUMN_SIZE], int result[] [COLUMN_SIZE], int rowSize){for (int i = 0; i < COLUMN_SIZE; i++)for (int j = 0; j < COLUMN_SIZE; j++)for (int k = 0; k < COLUMN_SIZE; k++)result[i] [j] += a[i] [k] * b[k] [j];}/** Print result */void printResult(int m1[] [COLUMN_SIZE], int m2[] [COLUMN_SIZE], int m3[] [COLUMN_SIZE], char op, int rowSize){for (int i = 0; i < rowSize; i++){for (int j = 0; j < COLUMN_SIZE; j++)cout << " " << m1[i] [j];if (i == COLUMN_SIZE / 2)cout << " " << op << " ";elsecout << " ";for (int j = 0; j < COLUMN_SIZE; j++)cout << " " << m2[i] [j];if (i == COLUMN_SIZE / 2)cout << " = ";elsecout << " ";for (int j = 0; j < COLUMN_SIZE; j++)cout << " " << m3[i] [j];cout << endl;}}int main(){// Create two matrices as two dimensional arraysint matrix1[5] [5];int matrix2[5] [5];int result[5] [5];// Assign random values to matrix1 and matrix2for (int i = 0; i < 5; i++)for (int j = 0; j < 5; j++){matrix1[i] [j] = rand();matrix2[i] [j] = rand();}multiplyMatrix(matrix1, matrix2, result, 5);cout << "The multiplication of the matrices is " << endl; printResult(matrix1, matrix2, result, '*', 5);}Exercise6_24#include <iostream>using namespace std;int main(){int board[8] [8];for (int i = 0; i < 8; i++){for (int j = 0; j < 8; j++){board[i] [j] = rand() % 2;cout << board[i] [j];}cout << endl;}// Check rowsfor (int i = 0; i < 8; i++){bool same = true;for (int j = 1; j < 8; j++){if (board[i] [0] != board[i] [j]){same = false; break;}}if (same) cout << "All " << board[i] [0] << "'s on row " << i << endl;}// Check columnsfor (int j = 0; j < 8; j++){bool same = true;for (int i = 1; i < 8; i++){if (board[0] [j] != board[i] [j]){same = false; break;}}if (same) cout << "All " << board[0] [j] << "'s on column " << j << endl; }// Check major diagonalbool same = true;for (int i = 1; i < 8; i++){if (board[0] [0] == board[i] [i]){same = false; break;}}if (same) cout << "All " << board[0] [0] << "'s on major diagonal" << endl;// Check subdiagonalsame = true;for (int i = 1; i < 8; i++){if (board[0] [7] == board[i] [7 - i]){same = false; break;}}if (same) cout << "All " << board[0] [0] << "'s on subdiagonal" << endl;return 0;}Exercise6_26#include <iostream>#include <cmath>using namespace std;int lcm(int number1, int number2);int pow(int a, int b);int getPrimeFactors(int number, int table[][2]);int main(){// Enter two integersint number1;cout << "Enter the first integer: ";cin >> number1;int number2;cout << "Enter the second integer: ";cin >> number2;cout << "The LCM for " << number1 << " and " << number2 << " is " << lcm(number1, number2) << endl;}int lcm(int number1, int number2){int table1[100][2];for (int i = 0; i < 100; i++)for (int j = 0; j < 2; j++)table1[i][j] = 0;int i1 = getPrimeFactors(number1, table1);int table2[100][2];for (int i = 0; i < 100; i++)for (int j = 0; j < 2; j++)table2[i][j] = 0;int i2 = getPrimeFactors(number2, table2);int result = 1;int i = 0;int j = 0;while (i < i1 && j < i2){if (table1[i] [0] < table2[j] [0]){result *= pow(table1[i] [0], table1[i] [1]);i++;}else if (table1[i] [0] == table2[j] [0]){result *= pow(table1[i] [0], max(table1[i] [1], table2[j] [1]));i++;j++;}else{result *= pow(table2[j] [0], table2[j] [1]);j++;}}while (i < i1){result *= pow(table1[i] [0], table1[i] [1]);i++;}while (j < i2){result *= pow(table2[j] [0], table2[j] [1]);j++;}return result;}int pow(int a, int b){int result = 1;for (int i = 1; i <= b; i++)result *= a;return result;}int getPrimeFactors(int number, int table[][2]) {int i = 0;int factor = 2;while (factor <= number){if (number % factor == 0){table[i] [0] = factor;while (number % factor == 0){number = number / factor;table[i] [1] ++;}i++;}else{factor++;}}return i;}。
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语⾔程序设计第五版课后答案谭浩强第六章习题答案第六章:利⽤数组处理批量数据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语⾔程序设计(第五版)》习题答案各章习题参考答案第1章习题参考答案1. 简述C程序的结构特点。
答:(1) ⼀个C语⾔源程序由⼀个或多个源⽂件组成。
每个源⽂件由⼀个或多个函数构成,其中有且仅有⼀个主函数(main函数)。
(2) ⼀个函数由函数⾸部(即函数的第⼀⾏)和函数体(即函数⾸部下⾯的⼤括号内的部分)组成。
函数⾸部包括函数类型、函数名和放在圆括号内的若⼲个参数。
函数体由声明部分和执⾏部分组成。
(3) C程序书写格式⾃由,⼀⾏内可以写多条语句,⼀个语句也可以分写在多⾏中,每个语句必须以分号结尾。
(4)程序的注释内容放在“/*”和“*/之”间,在‘/’和‘*’之间不允许有空格;注释部分允许出现在程序中的任何位置处。
2. 分析例1.3程序的结构。
答:下⾯是例1.3的程序,它的结构是:有且只有⼀个主函数main以及若⼲个其它函数,还有⼀个被主函数调⽤的sumab函数。
函数有⾸部,包括类型和名称,⾸部下的⼤括号中有变量定义、输⼊、计算和输出等语句。
#includeint sumab (int x, int y); /*函数声明*/int main () /*主函数*/{ int a,b,sum; /*定义变量*/printf("请输⼊变量a与b的值:"); /*提⽰信息*/scanf ("%d %d", &a, &b); /*输⼊变量a和b的值*/sum=sumab(a,b); /*调⽤sumab函数*/printf("a与b的和等于%d", sum);/*输出sum的值*/return 0;}int sumab (int x, int y) /*定义sumab函数,并定义形参x、y */{ int z;z=x+y;return z;}3. 分别编写完成如下任务的程序,然后上机编译、连接并运⾏。
(1) 输出两⾏字符,第1⾏是“The computer is our good friends!”,第2⾏是“We learnC language.”。
第6章函数和模块设计【习题6-1】更正下面函数中的错误。
(1)返回求x和y平方和的函数。
(2)返回求x和y为直角边的斜边的函数。
sum_of_sq(x,y) hypot(double x,double y){ {double x,y; h=sqrt(x*x+y*y);return(x*x+y*y); return(h);} }程序如下:/*c6_1(1).c*/ /*c6_1(2).c*/(1) (2)double sum_of_sq(double x,double y) double hypot(double x,double y) { {return(x*x+y*y); double h;} h=sqrt(x*x+y*y);return(h);}【习题6-2】说明下面函数的功能。
(1)itoa(int n,char s[ ])(2)int htod(char hex [ ]){ { int i,dec=0;static int i=0,j=0; for(i=0;hex[i]!='\0';i++)int c; { if(hex[i]>='0'&&hex[i]<='9') if(n!=0) dec=dec*16+hex[i]-'0';{ if(hex[i]>='A'&&hex[i]<='F') j++; dec=dec*16+hex[i]-'A'+10;c=n%10+'0'; if(hex[i]>='a'&&hex[i]<='f') itoa(n/10,s); dec=dec*16+hex[i]-'a'+10;s[i++]=c; }} return(dec);else }{ (3)void stod(int n)if(j==0) s[j++]='0'; { int i;s[j]='\0'; if(n<0){ putchar('-');n=-n;} i=j=0; if((i=n/10)!=0) stod(i);} putchar(n%10+'0');} }功能:(1)(略)(2)(略)【习题6-3】编写已知三角形三边求面积的函数,对于给定的3个量(正值),按两边之和大于第三边的规定,判别其能否构成三角形,若能构成三角形,输出对应的三角形面积。