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 62 63 64 65 66 |
#include <iostream> #include <vector> #include <iomanip> // For std::fixed and std::setprecision // Constants const int MONTHS_IN_YEAR = 12; // SalesData class class SalesData { public: std::vector<double> monthlySales; SalesData() : monthlySales(MONTHS_IN_YEAR, 0.0) {} void recordSale(int month, double amount) { if (month >= 1 && month <= MONTHS_IN_YEAR) { monthlySales[month - 1] += amount; } else { std::cerr << "Invalid month: " << month << std::endl; } } double totalSales() const { double total = 0.0; for (double sale : monthlySales) { total += sale; } return total; } double averageSales() const { return totalSales() / MONTHS_IN_YEAR; } void printSales() const { std::cout << "Monthly Sales Data:" << std::endl; for (int i = 0; i < MONTHS_IN_YEAR; ++i) { std::cout << "Month " << (i + 1) << ": $" << std::fixed << std::setprecision(2) << monthlySales[i] << std::endl; } std::cout << "Total Sales: $" << std::fixed << std::setprecision(2) << totalSales() << std::endl; std::cout << "Average Monthly Sales: $" << std::fixed << std::setprecision(2) << averageSales() << std::endl; } }; int main() { SalesData sales; // Example sales data recording sales.recordSale(1, 5000.0); // January sales.recordSale(2, 4500.0); // February sales.recordSale(3, 6000.0); // March sales.recordSale(4, 7000.0); // April sales.recordSale(5, 6500.0); // May sales.recordSale(6, 8000.0); // June sales.recordSale(7, 7500.0); // July sales.recordSale(8, 9000.0); // August sales.recordSale(9, 8500.0); // September sales.recordSale(10, 9500.0); // October sales.recordSale(11, 10000.0); // November sales.recordSale(12, 11000.0); // December // Print out the sales data and statistics sales.printSales(); return 0; } |
Explanation:
- SalesData Class:
monthlySales
: A vector to store sales data for each month.recordSale(int month, double amount)
: Records a sale for a given month.totalSales() const
: Calculates the total sales for the year.averageSales() const
: Calculates the average sales per month.printSales() const
: Prints the sales data and statistics.
- Main Function:
- Creates a
SalesData
object. - Records sales data for each month (sample data).
- Prints the sales data and basic statistics (total and average sales).
- Creates a