C语言基础菜单驱动无全局变量汽油费用计算器作业技术咨询
Got it, let's refactor your existing code into a clean, menu-driven C program that eliminates global variables entirely. Global variables can make code harder to debug and maintain, so replacing them with local variables and structured data is a great move for a course project.
Key Improvements We'll Make
- Replace global variables with a struct to group related data (mileage, price per gallon, MPG, total cost)
- Build a simple text-based menu for user interaction
- Split functionality into modular functions that accept parameters instead of relying on globals
- Add input validation to handle invalid user entries (a nice touch for robustness)
Complete Refactored Code
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> // Struct to hold all calculator data (no globals needed!) typedef struct { float currentMileage; float pricePerGallon; float MPG; float totalCost; } GasCalculator; // Function prototypes void displayMenu(); void inputMileage(GasCalculator *calc); void inputPricePerGallon(GasCalculator *calc); void inputMPG(GasCalculator *calc); void calculateTotalCost(GasCalculator *calc); void displayResults(GasCalculator *calc); void clearScreen(); void pauseProgram(); int main() { GasCalculator calc = {0.0, 0.0, 0.0, 0.0}; // Initialize all values to 0 int choice; do { clearScreen(); displayMenu(); printf("Enter your choice: "); // Input validation for menu choice while (scanf("%d", &choice) != 1 || choice < 1 || choice > 6) { printf("Invalid input! Please enter a number between 1 and 6: "); // Clear invalid input from buffer while (getchar() != '\n'); } switch(choice) { case 1: inputMileage(&calc); break; case 2: inputPricePerGallon(&calc); break; case 3: inputMPG(&calc); break; case 4: calculateTotalCost(&calc); printf("Total cost calculated successfully!\n"); pauseProgram(); break; case 5: displayResults(&calc); pauseProgram(); break; case 6: printf("Exiting program...\n"); break; default: printf("Invalid choice! Please try again.\n"); pauseProgram(); } } while (choice != 6); return 0; } void displayMenu() { printf("=== Gas Cost Calculator Menu ===\n"); printf("1. Enter Current Mileage\n"); printf("2. Enter Price Per Gallon\n"); printf("3. Enter MPG (Miles Per Gallon)\n"); printf("4. Calculate Total Gas Cost\n"); printf("5. Display Results\n"); printf("6. Exit\n"); printf("===============================\n"); } void inputMileage(GasCalculator *calc) { clearScreen(); printf("Enter current mileage (miles): "); // Input validation for positive float while (scanf("%f", &calc->currentMileage) != 1 || calc->currentMileage < 0) { printf("Invalid input! Please enter a non-negative number: "); while (getchar() != '\n'); } printf("Mileage set to %.2f miles\n", calc->currentMileage); } void inputPricePerGallon(GasCalculator *calc) { clearScreen(); printf("Enter price per gallon ($): "); while (scanf("%f", &calc->pricePerGallon) != 1 || calc->pricePerGallon < 0) { printf("Invalid input! Please enter a non-negative number: "); while (getchar() != '\n'); } printf("Price per gallon set to $%.2f\n", calc->pricePerGallon); } void inputMPG(GasCalculator *calc) { clearScreen(); printf("Enter MPG (miles per gallon): "); while (scanf("%f", &calc->MPG) != 1 || calc->MPG <= 0) { printf("Invalid input! Please enter a positive number: "); while (getchar() != '\n'); } printf("MPG set to %.2f\n", calc->MPG); } void calculateTotalCost(GasCalculator *calc) { // Check if required values are set (avoid division by zero) if (calc->MPG <= 0 || calc->currentMileage < 0 || calc->pricePerGallon < 0) { printf("Error: Please enter valid mileage, price per gallon, and positive MPG first!\n"); return; } calc->totalCost = (calc->currentMileage / calc->MPG) * calc->pricePerGallon; } void displayResults(GasCalculator *calc) { clearScreen(); printf("=== Gas Cost Calculator Results ===\n"); printf("Current Mileage: %.2f miles\n", calc->currentMileage); printf("Price Per Gallon: $%.2f\n", calc->pricePerGallon); printf("MPG: %.2f\n", calc->MPG); // Only show total cost if it's been calculated (or values are valid) if (calc->MPG > 0 && calc->currentMileage >= 0 && calc->pricePerGallon >= 0) { printf("Total Gas Cost: $%.2f\n", calc->totalCost); } else { printf("Total Gas Cost: Not calculated (missing valid inputs)\n"); } printf("==================================\n"); } void clearScreen() { #ifdef _WIN32 system("cls"); #else system("clear"); #endif } void pauseProgram() { printf("\nPress any key to continue..."); while (getchar() != '\n'); // Clear buffer getchar(); // Wait for user input }
Key Explanations
- Struct Usage: The
GasCalculatorstruct groups all related data together, so we can pass a single pointer to functions instead of multiple individual variables. This keeps the code organized and avoids globals. - Menu Loop: The
do-whileloop inmain()keeps the menu running until the user chooses to exit. - Input Validation: Each input function checks for valid numbers (non-negative for mileage/price, positive for MPG) and clears invalid input from the buffer to prevent infinite loops.
- Modular Functions: Each function handles one specific task (input, calculation, display), making the code easier to read and modify.
- Cross-Platform Support: The
clearScreen()function works on both Windows and Unix-like systems.
This version is much more maintainable, follows best practices for C programming, and fits perfectly as a course assignment!
内容的提问来源于stack exchange,提问作者JustAHitman
相关产品推荐
相关产品推荐

