1.输入学号姓名,从键盘输入成绩,计算平均值
#include<string>
struct student
{
int num; //学号
string name ; //姓名
float score;
};
void Input(student stu[],int n) //输入成绩
{
for(int i=0;i<n;i++)
{
cin>>stu[i].score;
}
}
double Average(student stu[],int n)//计算平均值
{
double sum=0;
for(int i=0;i<n;i++) sum+=stu[i].score;
return(sum/n);
}
void Output(student stu[],int n)
{
for(int i=0;i<n;i++)
cout<<stu[i].name<<' '<<stu[i].num<<' '<<stu[i].score<<endl;
}
int main()
{
student stu[3]={{1,"su"},{2,"cao"},{3,"ma"}};
Input(stu,3);//注意数组做实参,写法
Output (stu,3);
double aver=Average(stu,3);
cout<<"Average="<<aver<<endl;
return 0;
}
结构体后面必须要有‘;’
结构体在后面也可以写成结构体数组形式。
一般情况下尽量用大写。
2.用左上角到右下角两个点计算矩形面积
#include<cmath>
#include<iomanip>
class CRect
{
private:
int left,top,right,bottom;//定义了四个坐标值,代表左上点和右下点
public:
void setcoord(int L,int T,int R,int B)//输入四个坐标值
{
left=L;top=T;right=R;bottom=B;
}
void getcoord(int *L,int *T,int *R,int *B)//将他们放入指针
{
*L=left; *T=top; *R=right; *B=bottom;
}
void print()//计算面积,注意abs绝对值
{
cout<<"Area="<<abs(right-left)*abs(bottom-top)<<endl;
}
};
int main()
{
CRect r1,r2;
int a,b,c,d;
r1.setcoord(100,300,50,200);//输入
r1.getcoord(&a,&b,&c,&d);//寻址
cout<<"left="<<a<<'\t'<<"top="<<b<<endl;
cout<<"rigth="<<c<<'\t'<<"bottom="<<d<<endl;
r1.print();
r2=r1; //可以进行这样的操作
r2.print();
return 0;
}
输入的时候是一个函数,防指针是另一个函数。