How to get C/C++ numbers and get the sum excluding the smallest and largest numbers.

Asked 2 years ago, Updated 2 years ago, 70 views

#include <iostream>

using namespace std;

int minmax(int num) {
    int value, sum;
    int min, max;

    min = 9999;
    max = 0;

    for (int i = 0; i < num; i++) {
        cout << "Enter your values please " << endl;
        cin >> value;
        sum += value;

        if (max  < value) {
            max = value;
        }
        else if (min > value) {
            min = value;
        }
    }
    return sum - max - min;
}

int main() {
    int n, res;
    cout << "Enter your number please " << endl;
    cin >> n;

    res = minmax(n);

    cout << "The summation of values execpt maximum and minimum is : " << res << endl;

    return 0;
}



This is my source code. If I enter 5, I can enter 5 numbers, right? So [1,2,3,4,5] When I entered [1,2,3,4,5], the expected output value is: 9, and the output value is -9996532. Could you tell me what the problem is?

c c++ for

2022-09-20 19:48

2 Answers

If it's self-made code, I think you can debug it and solve it. Practice finding bugs in your program, not easily seeking help from others.

At the end of the minmax function, take the min and max values (cout << "max:" << max <<" , min:" < min << endl;) and you'll find the bug in no time.


2022-09-20 19:48

Reset sum=0; if (max < value) { max = value; } if (min > value) { min = value; } You have to do it. If there is an else if statement when I put in 1, the value will be in max and not in min, right?


2022-09-20 19:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.