You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跟踪最小与最大值: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_val and max_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_val to an arbitrary small number or max_val to 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 for loop with a fixed count won’t work here—the exercise doesn’t specify how many values the user will enter. The while loop tied to cin is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:54:29