(1) 定义一个Student类,其中包括私有数据成员和公有成员函数,即
mId 学号
mMath 高等数学成绩
mEnglish 英语成绩
mProgramming 程序设计成绩
InScore() 输入学号和各科成绩,并且计算平均成绩
ShowScore() 输出学号和各科成绩
使用Student类,输入某班n(事先不能确定)个学生的学号和各科成绩,然后求各个学生的平均成绩,并列表输出学生的学号、各科成绩和平均成绩。
#include <iostream>
using namespace std;
class Student
{
private:
int mId;
double mMath;
double mEnglish;
double mProgramming;
double average;
public:
void InScore(int id,double math,double english,double progarmming)
{
mId = id;
mMath = math;
mEnglish = english;
mProgramming = progarmming;
average = (mMath + mEnglish + mProgramming) / 3;
}
void ShowScore()
{
cout << "\n" << "Id:" << mId << "\n" << "Math:" << mMath << "\n" <<
"English:" << mEnglish << "\n" << "Programming:" <<
mProgramming << "\n" << "Average:" << average << endl;
}
};
int main()
{
int size = 3;
Student* p = new Student[size];
int count = 0;
int id = 0;
double math = 0;
double eng = 0;
int pro = 0;
while (cin)//仅当输入的任意一个数据为小数或整数时进入循环
{
cout << "cin id, math, english, programming" << endl;
cin >> id >> math >> eng >> pro;
p[count].InScore(id,math,eng,pro);
count++;
if (count == size)
{
Student* temp = new Student[size + 3];
for (int i = 0; i < count; i++)
{
temp[i] = p[i];
}
delete[]p;
p = temp;
size += 3;
}
}
for (int i = 0; i < count - 1; i++)
{
p[i].ShowScore();
}
delete[]p;
p = nullptr;
}
(2)建立一个复数类Complex,其私有数据成员mX和mY表示复数的实部和虚部,构造函数Complex用于对复数的实部和虚部初始化,友员函数Add,Sub,Mul和Div分别用于进行复数的加、减、乘和除法运算,函数Show用于显示复数的内容。在主函数中,实例化两个复数,并输入一个运算符,按运算符选择相应的友员函数进行复数运算,然后输出运算结果。
#include <iostream>
#include <string>
using namespace std;
class Complex
{
friend Complex Add(Complex& x, Complex& y);
friend Complex Sub(Complex& x, Complex& y);
friend Complex Mul(Complex& x, Complex& y);
friend Complex Div(Complex& x, Complex& y);
public:
Complex(double x, double y) :mX(x), mY(y) {}
void Show()
{
if (mX == 0)
{
cout << showpos << mY << "i" << endl;
}
else if (mY == 0)
{
cout << noshowpos << mX << endl;
}
else
{
cout << noshowpos << mX << showpos << mY << "i" << endl;
}
}
private:
double mX;
double mY;
};
Complex Add(Complex& x, Complex& y)
{
Complex temp(0, 0);
temp.mX = x.mX + y.mX;
temp.mY = x.mY + y.mY;
return temp;
}
Complex Sub(Complex& x, Complex& y)
{
Complex temp(0, 0);
temp.mX = x.mX - y.mX;
temp.mY = x.mY - y.mY;
return temp;
}
Complex Mul(Complex& x, Complex& y)
{
Complex temp(0, 0);
temp.mX = x.mX * y.mX - x.mY * y.mY;
temp.mY = x.mY * y.mX + x.mX * y.mY;
return temp;
}
Complex Div(Complex& x, Complex& y)
{
Complex temp(0, 0);
temp.mX = (x.mX * y.mX + x.mY * y.mY) / (y.mX * y.mX + y.mY * y.mY);
temp.mY = (x.mY * y.mX - x.mX * y.mY) / (y.mX * y.mX + y.mY * y.mY);
return temp;
}
int main()
{
Complex x(1, 2);
Complex y(3, 4);
Complex z(0, 0);
x.Show();
y.Show();
string sym;
cout << "please cin the symbol( + - * / )" << endl;
cin >> sym;
if (sym == "+")
{
z = Add(x, y);
z.Show();
}
else if (sym == "-")
{
z = Sub(x, y);
z.Show();
}
else if (sym == "*")
{
z = Mul(x, y);
z.Show();
}
else if (sym == "/")
{
z = Div(x, y);
z.Show();
}
}