Min max mid

In class, we had to do a loop, and cout some of its stats; the count, mean, min, and max.
Using what I learned in class, I tried to see if I could figure out how to input 3 numbers and store the middle, not just the min and max.

I was sort of successful. It's a weird error. The code I am posting works sometimes, and other times it prints a weird number.

for instance, if 4 6 8 is input, it works fine. But if 10 1 4 is, the min and max are good, but the min is some negative number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 #include <iostream>
using namespace std;

int main(){
    
    float num;
    cin >> num;
    float max = num;
    float min = num;
    float difference;
    float diff;
    float mid = num;
   float middle;
    
    for (int i = 0; i <=1; i++)
        {                       
           cin >> num ;

                if (num > max) {
                    max = num; }

                if (num > mid) {
                    middle = mid; // kind of like a temp variable
                    mid = num; }

                if (num < min) {
                    min = num;
                               }            
      
    
        }
        cout << min << endl;
        cout << middle << endl;
        cout << max << endl;
You cannot rely on
1
2
3
                if (num > mid) {
                    middle = mid; // kind of like a temp variable
                    mid = num; }


We can take your example itself, when we give "10 1 4", middle is never assigned because the number is never greater than mid and remember you assigned mid to 10.

I really think you should avoid that for-loop when you're only working with three variables. I'm thinking of a good approach here but I think it would have to do with using an array (if you really had to us a for-loop).

Otherwise if you're just using three variables then just initialize three variables, find the min and the max, and find the middle by the classic (a+b+c)-(min+max). If you had to use a for-loop then treat the indexes of an array that would hold inputs as the variables, that's it.


Topic archived. No new replies allowed.