C++作业求助:读取文件中12个double值并完成指定函数实现
Alright, let's tackle this C++ assignment step by step. You've got the right start with reading 12 monthly rainfall values into an array—now let's fill in those missing functions and wrap up the main logic so your program works as intended.
First, let's outline what each function needs to do, then write the code with explanations:
1. The swap Function
This is a simple helper to swap two double values. We'll use pass-by-reference so the changes affect the original variables (no need for pointers or return values here).
void swap(double &a, double &b) { double temp = a; a = b; b = temp; }
2. The bubbleSort Function
We need to sort the rainfall array, but we should also keep track of which month each value belongs to. So we'll pass both the rainfall array and a corresponding month array to the sort function—this way, when we swap rainfall values, we swap their matching month names too to maintain accuracy.
void bubbleSort(double rainArray[], string monthArray[], int size) { bool swapped; for (int i = 0; i < size - 1; i++) { swapped = false; for (int j = 0; j < size - i - 1; j++) { // Sort from lowest to highest—reverse the > to < for highest to lowest if (rainArray[j] > rainArray[j + 1]) { swap(rainArray[j], rainArray[j + 1]); swap(monthArray[j], monthArray[j + 1]); } } // Early exit if no swaps happened (array is already sorted) if (!swapped) break; } }
3. The displayRainfall Function
This function will neatly print out the rainfall data with corresponding months. We'll use formatting tools to make the output clean and easy to read.
#include <iomanip> // Don't forget this header for formatting! void displayRainfall(const double rainArray[], const string monthArray[], int size, const string &title) { cout << "\n" << title << "\n"; cout << "-------------------------\n"; cout << left << setw(12) << "Month" << right << setw(10) << "Rainfall (in)\n"; cout << "-------------------------\n"; for (int i = 0; i < size; i++) { cout << left << setw(12) << monthArray[i] << right << setw(10) << fixed << setprecision(2) << rainArray[i] << "\n"; } }
4. Completing the main Function
Your main function needs to handle file input, array initialization, and calling your helper functions. We'll also add useful summary stats to make the program more complete:
#include <iostream> #include <fstream> #include <string> using namespace std; // Global month names (const so we don't accidentally modify them) const string MONTHS[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; const int NUM_MONTHS = 12; // Function declarations (put these before main) void swap(double &a, double &b); void bubbleSort(double rainArray[], string monthArray[], int size); void displayRainfall(const double rainArray[], const string monthArray[], int size, const string &title); int main() { double rainfall[NUM_MONTHS]; string monthsCopy[NUM_MONTHS]; // Copy of month names to sort (since MONTHS is const) // Copy the original month names to our sortable array for (int i = 0; i < NUM_MONTHS; i++) { monthsCopy[i] = MONTHS[i]; } // Open the input file ifstream inputFile("rainfall.txt"); // Replace with your actual file path/name if (!inputFile) { cerr << "Error: Could not open the rainfall data file!\n"; return 1; // Exit with error code } // Read 12 double values from the file for (int i = 0; i < NUM_MONTHS; i++) { if (!(inputFile >> rainfall[i])) { cerr << "Error: Invalid data found at month " << i + 1 << "\n"; inputFile.close(); return 1; } } inputFile.close(); // Show original unsorted data displayRainfall(rainfall, MONTHS, NUM_MONTHS, "Original Monthly Rainfall"); // Sort the data bubbleSort(rainfall, monthsCopy, NUM_MONTHS); // Show sorted data displayRainfall(rainfall, monthsCopy, NUM_MONTHS, "Sorted Rainfall (Low to High)"); // Calculate and display summary statistics double totalRain = 0.0; for (double rain : rainfall) { totalRain += rain; } double avgRain = totalRain / NUM_MONTHS; cout << "\n-------------------------\n"; cout << "Total Annual Rainfall: " << fixed << setprecision(2) << totalRain << " inches\n"; cout << "Average Monthly Rainfall: " << fixed << setprecision(2) << avgRain << " inches\n"; cout << "Highest Rainfall: " << monthsCopy[NUM_MONTHS - 1] << " - " << rainfall[NUM_MONTHS - 1] << " inches\n"; cout << "Lowest Rainfall: " << monthsCopy[0] << " - " << rainfall[0] << " inches\n"; return 0; }
Key Notes:
- Make sure to include all required headers (
iostream,fstream,string,iomanip). - The
MONTHSarray is declared asconstto protect the original month names—we use a copy (monthsCopy) for sorting so we can still display the original order later. - We added error checking for file opening and data reading—this handles cases where the file is missing or has invalid data.
- The formatting with
setw,fixed, andsetprecisionmakes the output look professional and easy to scan.
内容的提问来源于stack exchange,提问作者Garrett Wiggs

