跟踪最小与最大值:Stroustrup书籍编程习题求助
Hey there! Let's work through this exercise from Stroustrup's book together—it's a fundamental one for getting the hang of tracking values through loops. I’ll share a working implementation, break down the key parts, and point out common pitfalls to avoid.
Working Implementation Code
#include <iostream> using namespace std; int main() { double num; double min_val, max_val; // Start by reading the first value to initialize min and max cout << "Enter a series of double values (enter non-numeric input to stop): " << endl; if (!(cin >> num)) { cout << "No valid values were entered." << endl; return 1; } min_val = num; max_val = num; // Loop to read remaining values and update min/max while (cin >> num) { if (num < min_val) { min_val = num; } if (num > max_val) { max_val = num; } } // Output the final results cout << "Minimum value entered: " << min_val << endl; cout << "Maximum value entered: " << max_val << endl; return 0; }
Key Details to Note
- Smart Initialization: Instead of hardcoding initial values (like 0.0, which would fail if all inputs are negative or larger than 0), we use the first valid input to set both
min_valandmax_val. This ensures we start with a value that’s actually part of the user’s input set. - Continuous Input Loop: The
while (cin >> num)condition keeps reading values until the user enters a non-numeric character (like a letter) or presses the end-of-input shortcut (Ctrl+D on Unix/Linux, Ctrl+Z on Windows). - Update Logic: For each new number, we check if it’s smaller than the current minimum or larger than the current maximum, and update the respective variable if so.
- Edge Case Handling: The initial
if (!(cin >> num))check catches the scenario where the user doesn’t enter any valid numbers at all, preventing undefined behavior.
Common Mistakes to Fix
If your original code wasn’t working, here are a few things to check:
- Incorrect Initialization: If you set
min_valto an arbitrary small number ormax_valto an arbitrary large number, that can work but requires including extra headers and is less intuitive than using the first input. - Wrong Loop Structure: Using a
forloop with a fixed count won’t work here—the exercise doesn’t specify how many values the user will enter. Thewhileloop tied tocinis the right approach for unknown input lengths. - Missing One Comparison: It’s easy to accidentally only check for the minimum or only the maximum—make sure both checks are included in your loop.
内容的提问来源于stack exchange,提问作者Njgardner90
相关产品推荐
相关产品推荐

