c++综合练习1

93 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

6-1 Point类的声明和实现

定义一个Point类,代表平面上的一个点,其横坐标和纵坐标分别用x和y表示,设计Point类的成员函数,实现并测试这个类。
主函数中输入两个点的坐标,计算并输出了两点间的距离。请根据主函数实现Point类。

裁判测试程序样例:

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

//你的代码将被嵌在这里

int main()
{
    Point p1, p2;
    double x1, y1, x2, y2;
    cin >> x1 >> y1 >> x2 >> y2;
    p1.setX(x1);
    p1.setY(y1);
    p2.setX(x2);
    p2.setY(y2);
    double x = p1.getX() - p2.getX();
    double y = p1.getY() - p2.getY();
    double len = sqrt(x * x + y * y);
    cout << fixed << setprecision(2) << len << endl;
    return 0;
}

输入样例:

0 0 3 3

输出样例:

4.24

代码:

class Point{
	private:
		double a,b;
	public:
		Point(){}
		//Point(int x, int y):a(x),b(y){}
		double setX(double x1)
		{
			a = x1;
		}	
		double setY(double y1)
		{
			b = y1;
		}
		double getX()
		{
			return a;
		}	
		double getY()
		{
			return b;
		}
};

6-2 体育俱乐部(构造函数)

一个俱乐部需要保存它的简要信息,包括四项:名称(字符串),成立年份(整数),教练姓名(字符串)和教练胜率(0-100之间的整数)。用键盘输入这些信息后,把它们分两行输出:第一行输出名称和成立年份,第二行输出教练姓名和胜率。

裁判测试程序样例:

#include <iostream>
#include <string>
using namespace std;
class Coach{
    string name;
    int winRate;
public:
    Coach(string n, int wr){
        name=n; winRate=wr;
    }
    void show();
};
class Club{
    string name;
    Coach c;
    int year;
public:
    Club(string n1, int y, string n2, int wr);
    void show();
};
int main(){
    string n1, n2;
    int year, winRate;
    cin>>n1>>year>>n2>>winRate;
    Club c(n1,year, n2, winRate);
    c.show();
    return 0;
}

/* 请在这里填写答案 */

输入样例:

Guanzhou 2006 Tom 92

输出样例:

Guanzhou 2006
Tom 92%

代码:


Club::Club(string n1, int y, string n2, int wr):c(n2, wr)
{
	name = n1;
	year = y;
}
void Club::show()
{
	cout << name << " " << year <<endl;
	c.show();
} 
void Coach::show()
{
	cout << name << " " << winRate << "%" <<endl;
}

6-3 狗的继承

完成两个类,一个类Animal,表示动物类,有一个成员表示年龄。一个类Dog,继承自Animal,有一个新的数据成员表示颜色,合理设计这两个类,使得测试程序可以运行并得到正确的结果。

函数接口定义:

按照要求实现类

裁判测试程序样例:

/* 请在这里填写答案 */

int main(){
    Animal ani(5);
    cout<<"age of ani:"<<ani.getAge()<<endl;
    Dog dog(5,"black");
    cout<<"infor of dog:"<<endl;
    dog.showInfor();
}

输入样例:

输出样例:

age of ani:5
infor of dog:
age:5
color:black

代码:

#include <iostream>
#include <string>
using namespace std;
class Animal{
	private:
		int age;
	public:
		//Animal(){}
		Animal(int age):age(age){}
		int getAge()
		{
			return age;
		}
};
class Dog: public Animal{
	private:
		string color;
	public:
		//Dog(){}
		Dog(int ag, string co):color(co),Animal(ag){}
		void showInfor()
		{
			cout << "age:" << getAge() << endl;
			cout << "color:" << color << endl;
		}
};