This tutorial demonstrates how to use C++ vector to store and process temperature samples taken randomly throughout the day for an entire month. You’ll learn how to simulate random data, calculate daily statistics (min, max, average), and calculate monthly statistics. The program will use classes to organize the data and computations.
1. Program Overview
The program:
- Simulates random temperature samples for each day in a month.
- Uses a
vectorto store temperatures for each day. - Computes:
- Daily min, max, and average temperatures.
- Monthly min, max, and average temperatures.
2. Setting Up the Class Structure
We’ll define two classes:
DayTemperature: Handles temperature data and statistics for a single day.MonthTemperature: Manages temperature data and statistics for the entire month.
3. Code Implementation
Step 1: Include Necessary Libraries
#include <iostream>
#include <vector>
#include <cstdlib> // For rand()
#include <ctime> // For seeding random numbers
#include <algorithm> // For min_element, max_element, accumulate
using namespace std;
Step 2: Define the DayTemperature Class
class DayTemperature {
private:
vector temperatures;
public:
// Constructor to generate random temperatures
DayTemperature(int samples) {
for (int i = 0; i < samples; i++) {
temperatures.push_back((rand() % 800) / 10.0 - 30.0); // Random temperature between -30.0 and 50.0
}
}
// Get daily minimum temperature
double getMin() const {
return *min_element(temperatures.begin(), temperatures.end());
}
// Get daily maximum temperature
double getMax() const {
return *max_element(temperatures.begin(), temperatures.end());
}
// Get daily average temperature
double getAverage() const {
double sum = accumulate(temperatures.begin(), temperatures.end(), 0.0);
return sum / temperatures.size();
}
// Print daily temperatures (for debugging or visualization)
void printTemperatures() const {
for (double temp : temperatures) {
cout << temp << " ";
}
cout << endl;
}
};
Step 3: Define the MonthTemperature Class
class MonthTemperature {
private:
vector days;
public:
// Constructor to generate random temperatures for each day
MonthTemperature(int daysInMonth, int samplesPerDay) {
for (int i = 0; i < daysInMonth; i++) {
days.emplace_back(samplesPerDay); // Add a new DayTemperature object
}
}
// Get monthly minimum temperature
double getMonthlyMin() const {
double minTemp = numeric_limits::max();
for (const DayTemperature& day : days) {
minTemp = min(minTemp, day.getMin());
}
return minTemp;
}
// Get monthly maximum temperature
double getMonthlyMax() const {
double maxTemp = numeric_limits::lowest();
for (const DayTemperature& day : days) {
maxTemp = max(maxTemp, day.getMax());
}
return maxTemp;
}
// Get monthly average temperature
double getMonthlyAverage() const {
double totalSum = 0.0;
int totalSamples = 0;
for (const DayTemperature& day : days) {
totalSum += day.getAverage() * day.getTemperatures().size();
totalSamples += day.getTemperatures().size();
}
return totalSum / totalSamples;
}
// Print daily statistics
void printDailyStats() const {
for (size_t i = 0; i < days.size(); i++) {
cout << "Day " << i + 1 << ":\n";
cout << " Min: " << days[i].getMin() << "\n";
cout << " Max: " << days[i].getMax() << "\n";
cout << " Avg: " << days[i].getAverage() << "\n";
}
}
};
Step 4: Write the Main Program
int main() {
srand(time(0)); // Seed random number generator
const int daysInMonth = 30;
const int samplesPerDay = 10;
// Create a MonthTemperature object
MonthTemperature month(daysInMonth, samplesPerDay);
// Print daily statistics
month.printDailyStats();
// Print monthly statistics
cout << "\nMonthly Statistics:\n";
cout << " Min Temperature: " << month.getMonthlyMin() << "\n";
cout << " Max Temperature: " << month.getMonthlyMax() << "\n";
cout << " Average Temperature: " << month.getMonthlyAverage() << "\n";
return 0;
}
4. Explanation
Generating Random Temperatures
rand() % 800 / 10.0 - 30.0: Generates a random temperature between -30.0 and 50.0.
Daily Statistics
- Min: Using
std::min_element. - Max: Using
std::max_element. - Average: Using
std::accumulate.
Monthly Statistics
- Loop through all
DayTemperatureobjects to compute the overall min, max, and average temperatures for the month.
5. Example Output
Day 1:
Min: -12.3
Max: 28.4
Avg: 10.1
Day 2:
Min: -8.7
Max: 31.2
Avg: 14.5
...
Monthly Statistics:
Min Temperature: -15.8
Max Temperature: 49.3
Average Temperature: 12.8
6. Practice Enhancements
- Modify the program to allow user input for the number of days and samples per day.
- Store daily statistics in a separate vector for faster monthly calculations.
- Add functionality to output the results to a file.
This program showcases how std::vector can simplify managing and processing data while taking advantage of C++’s powerful algorithms and OOP principles. Experiment with the code and extend it to handle more complex scenarios!
