C++ 股票交易信息类:计算月度最大涨幅
C++ 股票交易信息类:计算月度最大涨幅
本文将介绍如何用 C++ 定义一个 Stock 类,记录一支股票交易的基本信息,包括交易日序号、当日最高价、当日最低价、当日开盘价和当日收盘价。我们将利用该类来计算一个月的最大涨幅。
1. 定义 Stock 类
class Stock {
private:
int day; // 交易日序号
double highestPrice; // 当日最高价
double lowestPrice; // 当日最低价
double openingPrice; // 当日开盘价
double closingPrice; // 当日收盘价
static double maxRise; // 静态数据成员,记录整个月最大涨幅
public:
Stock(int day, double highestPrice, double lowestPrice, double openingPrice, double closingPrice);
double getRise() const; // 计算当日涨幅
static double getMaxRise(); // 获取整个月最大涨幅
};
// 构造函数
Stock::Stock(int day, double highestPrice, double lowestPrice, double openingPrice, double closingPrice) {
this->day = day;
this->highestPrice = highestPrice;
this->lowestPrice = lowestPrice;
this->openingPrice = openingPrice;
this->closingPrice = closingPrice;
}
// 计算当日涨幅
double Stock::getRise() const {
return (closingPrice - openingPrice) / openingPrice;
}
// 获取整个月最大涨幅
double Stock::maxRise = 0.0;
double Stock::getMaxRise() {
return maxRise;
}
2. 主函数:存储股票信息并计算涨幅
int main() {
const int days = 30;
Stock stocks[days]; // 存储一个月的股票信息
// 初始化股票信息
for (int i = 0; i < days; i++) {
double highestPrice, lowestPrice, openingPrice, closingPrice;
cout << '第' << i + 1 << '天的股票信息:' << endl;
cout << '最高价:';
cin >> highestPrice;
cout << '最低价:';
cin >> lowestPrice;
cout << '开盘价:';
cin >> openingPrice;
cout << '收盘价:';
cin >> closingPrice;
stocks[i] = Stock(i + 1, highestPrice, lowestPrice, openingPrice, closingPrice);
}
// 计算每天的涨幅并输出
for (int i = 0; i < days; i++) {
Stock stock = stocks[i];
double rise = stock.getRise();
cout << '第' << i + 1 << '天的涨幅为:' << rise << endl;
// 更新整个月最大涨幅
if (rise > Stock::getMaxRise()) {
Stock::maxRise = rise;
}
}
// 输出整个月最大涨幅
cout << '整个月最大涨幅为:' << Stock::getMaxRise() << endl;
return 0;
}
3. 找出当月涨幅最大的股票
在上面的代码中,我们使用了一个静态数据成员 maxRise 来记录整个月最大涨幅。在计算每天的涨幅时,我们判断当前涨幅是否大于 maxRise,如果是,则更新 maxRise。最后输出 maxRise 即可得到当月最大涨幅。
代码说明:
- 静态数据成员
maxRise:该数据成员属于整个类,而不是某个特定对象。这意味着所有 Stock 对象共享同一个maxRise值。 getRise()方法:计算股票当日涨幅,用收盘价减去开盘价,除以开盘价。getMaxRise()方法:获取当前整个月最大涨幅。
总结:
本文展示了如何用 C++ 定义一个 Stock 类,记录股票交易的基本信息,并计算一个月的最大涨幅。代码中使用了静态数据成员来记录最大涨幅,并利用循环来更新最大涨幅。希望本文能够帮助您理解 C++ 编程中类和静态数据成员的应用。
原文地址: https://www.cveoy.top/t/topic/nn3f 著作权归作者所有。请勿转载和采集!