C++实验三
实验三 指针和数组
【实验目的】
1、掌握指针的概念、学会定义和使用指针变量;
2、学习使用指针数组和指向数组的指针;
【实验内容】
1、一个班有 5 名学生,每个学生修了五门课,求每个学生的平均成绩,并输出每个学生的学号,每门课程的成绩及平均值。求某门课程的平均分;
实现要求:
•分别编写2 个函数实现以上2 个要求,第1 个函数用数组名作参数,第2 个函数用指针用参数,并在函数体内用指针对数组操作。
2、编写一个程序,实现矩阵运算,具体要求如下:
•用函数addMatrix( int a[][COLUMN_SIZE], int b[][COLUMN_SIZE], int c[][COLUMN_SIZE], int rowSize)实现矩阵相加运算;
•用函数multiplyMatrix( int a[][COLUMN_SIZE], int b[][COLUMN_SIZE], int c[][COLUMN_SIZE], int rowSize)实现矩阵相乘运算;
•矩阵a和矩阵b的数据从键盘输入;
•输出矩阵相乘或相加结果即c矩阵的数据;
【实验要求】
1、编写实验内容要求的程序、编译并调试通过;
2、实验报告中记录编程过程中出现的错误与改正方法;
1 #include<iostream> 2 using namespace std; 3 struct Student 4 { 5 char NO[8]; 6 float score[5]; 7 }stu[5]; 8 float avrstu(float p[]) 9 { 10 float sum=0; 11 int j; 12 for(j=0;j<5;j++) 13 sum+=p[j]; 14 return sum/5.0; 15 } 16 float avrclass(float *p){ 17 float sum=0; 18 int j; 19 for(j=0;j<5;j++) 20 sum+=*(p+j); 21 return sum/5.0; 22 23 } 24 int main(){ 25 int i,j; 26 float pclass[5][5]; 27 double avrstu0; 28 cout<<"输入学生学号和5门课的成绩:"<<endl; 29 for(i=0;i<5;i++){ 30 cin>>stu[i].NO; 31 for(j=0;j<5;j++){ 32 cin>>stu[i].score[j]; 33 pclass[j][i]=stu[i].score[j]; 34 } 35 } 36 cout<<"各学生的学号和5门课成绩平均分:"<<endl; 37 for(i=0;i<5;i++){ 38 avrstu0=avrstu(stu[i].score); 39 cout<<stu[i].NO<<" "<<avrstu0<<endl;} 40 cout<<"5门课的平均分:"<<endl; 41 for(j=0;j<5;j++){ 42 cout<<avrclass(pclass[j])<<endl;} 43 return 0; 44 }
1 #include<iostream> 2 using namespace std; 3 const int COLUMN_SIZE=3; 4 const int rowSize=4; 5 void addMatrix( int a[][COLUMN_SIZE], int b[][COLUMN_SIZE], int c[][COLUMN_SIZE], int 6 7 rowSize) 8 { 9 int i,j; 10 for(i=0;i 11 for(j=0;j 12 c[i][j]=a[i][j]+b[i][j]; 13 } 14 } 15 void multiplyMatrix( int a[][COLUMN_SIZE], int b[][COLUMN_SIZE], int c[][COLUMN_SIZE], int 16 17 rowSize) 18 { 19 int i,j; 20 for(i=0;i 21 for(j=0;j 22 c[i][j]=a[i][j]*b[i][j]; 23 } 24 } 25 int main(){ 26 int a[rowSize][COLUMN_SIZE],b[rowSize][COLUMN_SIZE],c[rowSize][COLUMN_SIZE]; 27 int i,j,type; 28 for(i=0;i 29 for(j=0;j 30 cin>>a[i][j]; 31 } 32 for(i=0;i 33 for(j=0;j 34 cin>>b[i][j]; 35 } 36 cout<<"please choose which type do you want,1 stand for'+',2 stand for'*':"<<endl; 37 cin>>type; 38 if(type==1){ 39 addMatrix(a,b,c,rowSize); 40 for(i=0;i 41 for(j=0;j 42 cout<<c[i][j]<<" "; 43 if(j==COLUMN_SIZE-1) cout<<endl;} 44 } 45 } 46 else{ 47 multiplyMatrix(a,b,c,rowSize); 48 for(i=0;i 49 for(j=0;j 50 cout<<c[i][j]<<" "; 51 if(j==COLUMN_SIZE-1) cout<<endl;} 52 } 53 } 54 return 0; 55 }