用c++实现这个普通卡的余额,并且可以输入多组数据进行计算
时间: 2024-03-18 10:41:08 浏览: 17
好的,以下是用C++实现普通卡余额计算的代码,可以输入多组数据进行计算。具体实现过程中,我将设计一个Card基类,派生出CommonCard类,用于计算普通卡余额。
```
#include <iostream>
#include <iomanip>
using namespace std;
class Card {
protected:
double balance;
public:
Card(double b) : balance(b) {}
virtual ~Card() {}
virtual void TakeSubway(int month, int price) = 0;
virtual void Print() = 0;
};
class CommonCard : public Card {
private:
int count = 0;
int last_month = 0;
public:
CommonCard(double b) : Card(b) {}
virtual ~CommonCard() {}
virtual void TakeSubway(int month, int price) {
if (month != last_month) {
count = 0;
last_month = month;
}
if (count < 15) {
balance -= price;
count++;
}
else if (count >= 15) {
balance -= price * 0.6;
count++;
}
if (balance < 0) {
balance += price;
count--;
cout << "Please Recharge!" << endl;
}
}
virtual void Print() {
cout << count << " " << fixed << setprecision(2) << balance << endl;
}
};
int main() {
int n;
double balance;
cin >> balance >> n;
for (int i = 0; i < n; i++) {
int month, price;
cin >> month >> price;
CommonCard card(balance);
card.TakeSubway(month, price);
card.Print();
balance = card.balance;
}
return 0;
}
```
代码中,Card类为基类,包含一个保护成员变量balance,以及一个纯虚函数TakeSubway(int month, int price)和Print()。CommonCard类为Card类的一个派生类,实现了TakeSubway函数和Print函数,并添加了一些新的成员变量和成员函数。
在主函数中,我们首先输入初始余额和测试样例数n,然后进入循环,输入每次乘坐地铁的月份和票价,创建一个CommonCard对象,调用TakeSubway函数和Print函数,同时更新初始余额。循环结束后程序结束。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)