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

C++多输入整数求最值程序设计求助(禁用数组、条件运算符)

Solution for Your C++ Assignment

Hey there! No need to stress—we can solve this problem easily without arrays, the ternary operator, or any advanced stuff you haven't learned yet. Here's how to do it:

Key Idea

Instead of storing all numbers at once (which would need an array), we'll process each number as we read it:

  1. First, get the number of integers the user wants to input.
  2. Read the first number and use it to set our initial maximum and minimum values (since it's the only number we have so far).
  3. For every subsequent number, compare it to our current max and min. If it's bigger than the max, update the max. If it's smaller than the min, update the min. That's it!

Complete Code

#include <iostream>
using namespace std;

int main() {
    int count;
    // Ask user for the number of integers
    cout << "How many integers would you like to enter? ";
    cin >> count;

    // Make sure the count is at least 1 (matches your requirement)
    while (count < 1) {
        cout << "Please enter a number ≥ 1: ";
        cin >> count;
    }

    int currentNum, maxVal, minVal;
    // Read the first integer to initialize our max and min
    cout << "Please enter " << count << " integers. ";
    cin >> currentNum;
    maxVal = currentNum;
    minVal = currentNum;

    // Loop through the remaining integers
    for (int i = 1; i < count; ++i) {
        cin >> currentNum;
        // Update max if current number is larger
        if (currentNum > maxVal) {
            maxVal = currentNum;
        }
        // Update min if current number is smaller
        if (currentNum < minVal) {
            minVal = currentNum;
        }
    }

    // Print the final results
    cout << "min: " << minVal << " max: " << maxVal << endl;
    return 0;
}

How It Works

Let's walk through your example input to see it in action:

How many integers would you like to enter? 4
Please enter 4 integers. -4 105 2 -7

  1. We first read count = 4.
  2. The first number is -4—we set maxVal = -4 and minVal = -4.
  3. Next number is 105: since 105 > -4, we update maxVal to 105.
  4. Next number is 2: it's not bigger than 105 or smaller than -4, so no changes.
  5. Last number is -7: since -7 < -4, we update minVal to -7.
  6. Finally, we output min: -7 max: 105—exactly what your example shows!

This approach uses only basic loops and if statements, which I assume you've already learned. It doesn't rely on arrays or the ternary operator, so it fits all your assignment requirements.

内容的提问来源于stack exchange,提问作者Aaron Vaughan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:47:29