1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
#include <iostream> #include <vector> #include <cstdlib> #include <ctime> #include <iomanip> // Class to represent a stock class Stock { public: Stock(const std::string& name, double initialPrice) : name(name), price(initialPrice) {} // Method to update the stock price with random fluctuations void updatePrice() { // Generate a random percentage change between -5% and +5% double percentageChange = (rand() % 10001 - 5000) / 100.0; double change = price * (percentageChange / 100.0); price += change; // Ensure the price doesn't drop below zero if (price < 0) price = 0; } // Method to print the stock information void printInfo() const { std::cout << std::fixed << std::setprecision(2) << name << " | Price: $" << price << std::endl; } private: std::string name; double price; }; int main() { srand(time(0)); // Seed the random number generator // Create a list of stocks std::vector<Stock> stocks = { Stock("AAPL", 150.00), Stock("GOOGL", 2800.00), Stock("AMZN", 3400.00) }; const int simulationSteps = 10; // Number of simulation steps for (int step = 0; step < simulationSteps; ++step) { std::cout << "Step " << (step + 1) << ":\n"; // Update and print the information for each stock for (auto& stock : stocks) { stock.updatePrice(); stock.printInfo(); } std::cout << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); // Simulate time passing } return 0; } |
Explanation
- Stock Class:
- Attributes:
name
: Name of the stock.price
: Current price of the stock.
- Methods:
updatePrice()
: Updates the stock price with a random percentage change between -5% and +5%. Ensures the price does not go below zero.printInfo()
: Prints the current stock name and price, formatted to two decimal places.
- Attributes:
- Main Function:
- Random Number Generation:
srand(time(0))
seeds the random number generator to ensure different results each run. - Stocks Initialization: Creates a list of
Stock
objects with initial prices. - Simulation Loop: Runs for a set number of steps (10 in this case). For each step:
- Updates the price of each stock.
- Prints the updated stock information.
- Waits for 1 second to simulate time passing.
- Random Number Generation:
Usage
- Stock Simulation: The program simulates price changes for stocks, providing a basic model of stock market trends.
- Price Fluctuations: The
updatePrice()
method applies random changes to simulate market fluctuations.