本文已参与「新人创作礼」活动,一起开启掘金创作之路。
6-4 汽车收费
现在要开发一个系统,管理对多种汽车的收费工作。
给出下面的一个基类框架
class Vehicle
{
protected:
string NO;
public:
Vehicle(string n){
NO = n;
}
virtual int fee()=0;//计算应收费用
};
以Vehicle为基类,构建出Car、Truck和Bus三个类。
Car的收费公式为: 载客数8+重量2
Truck的收费公式为:重量*5
Bus的收费公式为: 载客数*3
生成上述类并编写主函数。
主函数根据输入的信息,相应建立Car,Truck或Bus类对象,对于Car给出载客数和重量,Truck给出重量,Bus给出载客数。假设载客数和重量均为整数
输入格式:第一行输入测试用例数。接着每个测试用例占一行,每行给出汽车的基本信息,第一个数据为当前汽车的类型:1为car,2为Truck,3为Bus。第二个数据为它的编号,接下来Car是载客数和重量,Truck要求输入重量,Bus要求输入载客数。
要求输出各车的编号和收费。
裁判测试程序样例:
#include<iostream>
#include <string>
using namespace std;
class Vehicle
{
protected:
string NO;//编号
public:
Vehicle(string n){ NO = n; }
virtual int fee()=0;//计算应收费用
};
/* 请在这里填写答案 */
int main()
{
Car c("",0,0);
Truck t("",0);
Bus b("",0);
int i, repeat, ty, weight, guest;
string no;
cin>>repeat;
for(i=0;i<repeat;i++){
cin>>ty>>no;
switch(ty){
case 1: cin>>guest>>weight; c=Car(no, guest, weight); cout<<no<<' '<<c.fee()<<endl; break;
case 2: cin>>weight; t=Truck(no, weight); cout<<no<<' '<<t.fee()<<endl; break;
case 3: cin>>guest; b=Bus(no, guest); cout<<no<<' '<<b.fee()<<endl; break;
}
}
return 0;
}
输入样例:
4
1 002 20 5
3 009 30
2 003 50
1 010 17 6
输出样例:
002 170
009 90
003 250
010 148
代码:
class Car:public Vehicle{
private:
int g1, w1;
public:
//Car(){}
Car(string no, int g1, int w1):Vehicle(no),g1(g1), w1(w1){}
virtual int fee()
{
return g1*8+w1*2;
}
};
class Truck:public Vehicle{
private:
int w2;
public:
//Truck(){}
Truck(string no, int w2):Vehicle(no),w2(w2){}
virtual int fee()
{
return w2*5;
}
};
class Bus:public Vehicle{
private:
int g2;
public:
//Bus(){}
Bus(string no, int g2):Vehicle(no),g2(g2){}
virtual int fee()
{
return g2*3;
}
};
6-5 学生成绩的输入和输出(运算符重载)
现在需要输入一组学生的姓名和成绩,然后输出这些学生的姓名和等级。
输入时,首先要输入学生数(正整数)N。接着输入N组学生成绩,每组成绩包括两项:第一项是学生姓名,第二项是学生的成绩(整数)。
输出时,依次输出各个学生的序号(从1开始顺序编号),学生姓名,成绩等级(不小于60为PASS,否则为FAIL)
函数接口定义:
面向Student类对象的流插入和流提取运算符
裁判测试程序样例:
#include <iostream>
#include <string>
using namespace std;
/* 请在这里填写答案 */
int main(){
int i, repeat;
Student st;
cin>>repeat;
for(i=0;i<repeat;i++){
cin>>st;
cout<<st<<endl;
}
return 0;
}
输入样例:
3
Li 75
Zhang 50
Yang 99
输出样例:
1. Li PASS
2. Zhang FAIL
3. Yang PASS
代码:
class Student{
private:
string name;
int score;
public:
static int num;
Student(){}
Student(string name, int score):name(name),score(score){}
friend istream& operator>>(istream& is, Student& s)
{
is >> s.name >> s.score;
return is;
}
friend ostream& operator<<(ostream& os, Student& s)
{
num++;
os << s.num << ". " << s.name << " ";
if(s.score>=60)
os << "PASS";
else
os << "FAIL";
return os;
}
};
int Student::num = 0;