C++ 模拟炒股软件代码示例
以下是一个简单的模拟炒股软件的代码示例:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 股票类
class Stock {
public:
Stock(string n, double p) : name(n), price(p) {}
string getName() { return name; }
double getPrice() { return price; }
void setPrice(double p) { price = p; }
private:
string name;
double price;
};
// 用户类
class User {
public:
User(string n, double m) : name(n), money(m) {}
string getName() { return name; }
double getMoney() { return money; }
void setMoney(double m) { money = m; }
void buy(Stock& s, int count);
void sell(Stock& s, int count);
private:
string name;
double money;
vector<pair<Stock, int>> stocks; // 股票和持有数量
};
void User::buy(Stock& s, int count) {
double total_cost = s.getPrice() * count;
if (total_cost > money) {
cout << 'Not enough money.' << endl;
return;
}
for (auto& p : stocks) {
if (p.first.getName() == s.getName()) {
p.second += count;
money -= total_cost;
cout << 'Buy ' << count << ' ' << s.getName() << ' stocks successfully.' << endl;
return;
}
}
stocks.push_back(make_pair(s, count));
money -= total_cost;
cout << 'Buy ' << count << ' ' << s.getName() << ' stocks successfully.' << endl;
}
void User::sell(Stock& s, int count) {
double total_income = s.getPrice() * count;
for (auto it = stocks.begin(); it != stocks.end(); it++) {
if (it->first.getName() == s.getName()) {
if (it->second < count) {
cout << 'Not enough stocks to sell.' << endl;
return;
}
it->second -= count;
money += total_income;
cout << 'Sell ' << count << ' ' << s.getName() << ' stocks successfully.' << endl;
if (it->second == 0) {
stocks.erase(it);
}
return;
}
}
cout << 'You don't have any ' << s.getName() << ' stocks.' << endl;
}
// 股票市场类
class Market {
public:
Market() {
stocks.push_back(Stock('Apple', 150.0));
stocks.push_back(Stock('Google', 200.0));
stocks.push_back(Stock('Microsoft', 120.0));
}
void showStocks() {
cout << 'Stocks in the market:' << endl;
for (auto& s : stocks) {
cout << s.getName() << ' ' << s.getPrice() << endl;
}
}
Stock& getStock(string name) {
for (auto& s : stocks) {
if (s.getName() == name) {
return s;
}
}
throw 'Stock not found.';
}
private:
vector<Stock> stocks;
};
int main() {
Market market;
User user('Alice', 1000.0);
market.showStocks();
user.buy(market.getStock('Apple'), 10);
user.buy(market.getStock('Google'), 5);
user.sell(market.getStock('Microsoft'), 3);
user.sell(market.getStock('Apple'), 5);
user.buy(market.getStock('Microsoft'), 8);
cout << 'User ' << user.getName() << ' has ' << user.getMoney() << ' dollars.' << endl;
cout << 'User ' << user.getName() << ' has the following stocks:' << endl;
for (auto& p : user.stocks) {
cout << p.first.getName() << ' ' << p.second << endl;
}
return 0;
}
该模拟炒股软件包含股票类、用户类和股票市场类。用户可以通过购买和卖出股票来进行投资,股票市场包含了一些股票,用户可以在其中进行选择。在这个示例中,用户可以购买股票、卖出股票,并且可以查看自己的账户余额和持有的股票。
原文地址: https://www.cveoy.top/t/topic/kz2b 著作权归作者所有。请勿转载和采集!