用CPP 写一个简单交易系统
时间: 2023-10-18 17:04:48 浏览: 44
好的,很高兴为您解答。下面是一个简单的交易系统的 CPP 代码,仅供参考。需要注意的是,这仅仅是一个示例,实际应用中还需要考虑很多复杂情况。
```C++
#include <iostream>
#include <string>
using namespace std;
class Trade {
public:
Trade(int initialValue) {
account = initialValue;
}
int getAccount() {
return account;
}
void buy(int amount, int price) {
account -= amount * price;
}
void sell(int amount, int price) {
account += amount * price;
}
private:
int account;
};
int main() {
Trade myTrade(100000);
cout << "Welcome to my trade system!" << endl;
while (true) {
cout << "Current account balance: " << myTrade.getAccount() << endl;
cout << "What would you like to do? (buy/sell/exit)" << endl;
string command;
cin >> command;
if (command == "buy") {
int amount, price;
cout << "How much do you want to buy? ";
cin >> amount;
cout << "At what price? ";
cin >> price;
myTrade.buy(amount, price);
cout << "Bought " << amount << " at " << price << endl;
} else if (command == "sell") {
int amount, price;
cout << "How much do you want to sell? ";
cin >> amount;
cout << "At what price? ";
cin >> price;
myTrade.sell(amount, price);
cout << "Sold " << amount << " at " << price << endl;
} else if (command == "exit") {
cout << "Goodbye!" << endl;
break;
} else {
cout << "Invalid command: " << command << endl;
}
}
return 0;
}
```
希望这个代码对您有所帮助。如果您还有其他问题,欢迎继续提问。