mooc程序设计与算法(三)C++面向对象程序设计 类和构造函数基础作业答案

001:编程填空:学生信息处理程序
总时间限制: 1000ms 内存限制: 1024kB
描述
实现一个学生信息处理程序,计算一个学生的四年平均成绩。

要求实现一个代表学生的类,并且类中所有成员变量都是【私有的】。

补充下列程序中的 Student 类以实现上述功能。

#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <cstdlib>
using namespace std;

class Student {
private:
    char name[20], id[15], c;
    int age;
    double s1,s2,s3,s4, e_s;
public:
    void  input(){
        cin.getline(name, 20, ',');//这里注意分割的用法
        cin>>age>>c;
        cin.getline(id, 15, ',');
        cin>>s1>>c>>s2>>c>>s3>>c>>s4;
    };
    void calculate(){
        e_s = (s1+s2+s3+s4)/4;
    };
    void output(){cout<<name<<c<<age<<c<<id<<c<<e_s<<endl;};

};

int main() {
    Student student;        // 定义类的对象
    student.input();        // 输入数据
    student.calculate();    // 计算平均成绩
    student.output();       // 输出数据
}

002:奇怪的类复制
查看 提交 统计 提问
总时间限制: 1000ms 内存限制: 65536kB
描述
程序填空,使其输出9 22 5

#include <iostream>
using namespace std;
class Sample {
public:
    int v;

    Sample(){}//无参构造函数
    Sample(int a):v(a){}//构造函数
    Sample(const Sample& a){
        v = a.v+2;
    }
};
void PrintAndDouble(Sample o)
{
    cout << o.v;
    cout << endl;
}
int main()
{
    Sample a(5);
    Sample b = a;
    PrintAndDouble(b);
    Sample c = 20;
    PrintAndDouble(c);
    Sample d;
    d = a;
    cout << d.v;
    return 0;
}

003:超简单的复数类
查看 提交 统计 提问
总时间限制: 1000ms 内存限制: 65536kB
描述
下面程序的输出是:

3+4i
5+6i

请补足Complex类的成员函数。不能加成员变量。

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Complex {
private:
    double r,i;
public:
    void Print() {
        cout << r << "+" << i << "i" << endl;
    }
Complex(){}
    Complex(char*str1){
        string str = str1;
        string s1 = str.substr(0, str.find("+"));
        string s2 = str.substr(str.find("+")+1, str.length()-str.find("+")-2);
        char *s_c1 = (&s1[0]);
        char *s_c2 = (&s2[0]);
        r = atof(s_c1);
        i = atof(s_c2);
    }
};
int main() {
    Complex a;
    a = "3+4i"; a.Print();
    a = "5+6i"; a.Print();
    return 0;
}

004:哪来的输出

#include <iostream>
using namespace std;
class A {
    public:
        int i;
        A(int x) { i = x; }
~A(){
        cout<<i<<endl;
    }
};
int main()
{
    A a(1);
    A * pa = new A(2);
    delete pa;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/abc15766228491/article/details/79862880
今日推荐