题目一
1:问题
编写一个程序,输入N个学生数据,包括学号、姓名、成绩,要求输出这些学生数据并计算平均分。 输入第一行为学生个数,接下来输入N个学生的数据。输出时,先输出N个学生,再输出平均分数(保留小数点后两位)。 样例输入: 3 test1 101 90 test2 102 87 tets3 103 83 样例输出: test1 101 90 test2 102 87 tets3 103 83 86.67
2.解题思路:
构造学生类,包括学号、姓名、成绩和输出函数。然后构造n个对象。
3.代码实现
#include<iostream>
#include<string.h>
#include<iomanip>
using namespace std;
class Student
{
public:
int getgrade()const
{return grade;}
void in(char a[40],int b,int c)
{
strcpy(name,a);
number=b;
grade=c;
}
void show()const
{
cout<<name<<" "<<number<<" "<<grade<<"\n";
}
private:
int grade;
int number;
char name[40];
};
void print(int i)
{
int j,b,c;
float sum;
char a[40];
Student student[i];
for(j=0,sum=0;j<i;j++)
{
cin>>a>>b>>c;
student[j].in(a,b,c);
}
for(j=0,sum=0;j<i;j++)
{
student[j].show();
sum+=student[j].getgrade();
}
cout<<fixed<<setprecision(2)<<sum/i;
}
int main()
{
int i;
cin>>i;
print(i);
}
4.问题及解决方法
问题:外部函数想要使用成绩,如何既不破坏封装性,又可以使用成绩 解决:在public下构造函数,返回值为int,函数体内返回grade 问题:如何控制输出格式 解决:用setprecision函数控制输出格式,或者使用c语言中的printf控制输出格式
5.心得:
C++是由C发展来的,用C中的输入输出语句控制输入输出格式非常方便,可以使用,面向对象的程序设计语言封装性十分重要,一般不能将数据作为公有,但是可以使用公有函数来调用私有数据。
题目二
1:问题
设计一个矩形类(Rectangle),属性为矩形的左下和右上角的坐标,矩形水平放置。计算并输入矩形的周长和面积。 输入第一行为左下坐标,第二行为右上坐标。 输出第一行为周长,第二行为面积。 样例输入: 0 0 5 5 样例输出: 20 25
2.解题思路
用数组表示坐标如a[2]
3.代码实现
#include<iostream>
using namespace std;
class REC
{
private:
int a[2],b[2];
public:
void scan()
{
cin>>a[0]>>a[1]>>b[0]>>b[1];
}
void longs()
{
cout<<2*(b[0]-a[0])+2*(b[1]-a[1]);
cout<<endl;
cout<<(b[0]-a[0])*(b[1]-a[1]);
}
};
int main()
{
REC a;
a.scan();
a.longs();
return 0;
}
题目三
1:问题
现有circle和rectangle两个类,其中,circle类的成员rad表示半径,rectangle类中成员x与y分别表示矩形的长和宽,定义二者的友元函数totalarea(),计算圆与矩形的面积之和。程序的第一行输入圆的半径,第二行分别输入矩形的长与宽。输出为二者的面积之和。 注:圆周率取值为3.14。 样例输入: 4 8 6 样例输出: 98.24
2:解决思路
用circle和rectangle二者的友元函数来计算面积和输出
3.代码实现
#include<cstring>
#include<iostream>
#include<cstdio>
using namespace std;
class Rectangle;
class Circle
{
private:
int rad;
public:
friend void totalarea(Circle& a,Rectangle& b);
void get()
{
cin>>rad;
}
};
class Rectangle
{
private:
int x,y;
public:
friend void totalarea(Circle& a,Rectangle& b);
void get()
{
cin>>x>>y;
}
};
void totalarea(Circle& a,Rectangle& b)
{
float sum;
sum=3.14*a.rad*a.rad+b.x*b.y;
printf("%.2f",sum);
};
int main()
{
Circle circle;
Rectangle rectangle;
circle.get();
rectangle.get();
totalarea(circle,rectangle);
return 0;
}
4.问题及解决方法
问题:输出的位置放在哪里 解决:用友元函数同时实现计算和输出,可以简化代码
5.心得:
友元函数可以使得一般函数可以访问类的私有成员,在俩个类必须相互关联时友元函数起着重要的作用,但是,它破坏了封装性,所以要分析利弊,确定是否使用友元函数