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 67 68 69 70 71 72 73 74 75 76 77 78 79 |
#include <iostream> #include <vector> #include <cstdlib> #include <ctime> #include <numeric> #include <algorithm> class DataAnalytics { public: DataAnalytics(int size) : dataSize(size) { // Initialize random number generator std::srand(std::time(0)); } void generateData() { data.clear(); for (int i = 0; i < dataSize; ++i) { data.push_back(std::rand() % 100 + 1); // Random data between 1 and 100 } } void displayData() const { std::cout << "Generated Data: "; for (int value : data) { std::cout << value << " "; } std::cout << std::endl; } double calculateMean() const { double sum = std::accumulate(data.begin(), data.end(), 0.0); return sum / dataSize; } double calculateMedian() { std::vector<int> sortedData = data; std::sort(sortedData.begin(), sortedData.end()); if (dataSize % 2 == 0) { return (sortedData[dataSize / 2 - 1] + sortedData[dataSize / 2]) / 2.0; } else { return sortedData[dataSize / 2]; } } int calculateMode() { std::unordered_map<int, int> frequency; for (int value : data) { frequency[value]++; } int mode = data[0]; int maxCount = 0; for (const auto& pair : frequency) { if (pair.second > maxCount) { maxCount = pair.second; mode = pair.first; } } return mode; } private: int dataSize; std::vector<int> data; }; int main() { const int dataSize = 10; DataAnalytics analytics(dataSize); analytics.generateData(); analytics.displayData(); std::cout << "Mean: " << analytics.calculateMean() << std::endl; std::cout << "Median: " << analytics.calculateMedian() << std::endl; std::cout << "Mode: " << analytics.calculateMode() << std::endl; return 0; } |
Explanation
- Header Files:
<iostream>
: For input and output operations.<vector>
: To use thestd::vector
Advertisement<cstdlib>
: For functions likestd::rand()
andstd::srand()
.<ctime>
: For thestd::time()
function to seed the random number generator.<numeric>
: Forstd::accumulate()
Advertisement<algorithm>
: Forstd::sort()
used in sorting the data.
- DataAnalytics Class:
- Constructor: Initializes the random number generator seed based on the current time.
- generateData(): Fills the
data
vector with random integers between 1 and 100. - displayData(): Outputs the generated data.
- calculateMean(): Computes the average of the data.
- calculateMedian(): Computes the median value by sorting the data and finding the middle value.
- calculateMode(): Finds the most frequently occurring value in the data.
Advertisement - main() Function:
- Creates an instance of
DataAnalytics
with a data size of 10. - Generates and displays random data.
- Computes and prints the mean, median, and mode of the data.
- Creates an instance of