Median of three

Back to Problem Solutions forum

mattdiflorio     2016-11-21 12:26:05

Hi guys,

I am currently baffled by the output that I am getting for my Median of Three code.

I believe that I have the correct if statements to output the median. As when I run the code I get correct results.

However, the code is skipping through the for loop and not always returning an output. So if it needs to loop through 25 times, sometimes it will only give me an output 22 times or it will only output 24 times. Some times it skips an entire chunk in the middle. It seems to vary on the different input data given and every time I compile it. If anyone can point me in the direction of what I am doing wrong that would be awesome!

Further, I apologise if I made a mistake with this post. I would like to make the code private, but seeing as I haven't solved it either I cannot post it private. If someone could help me fix that.

#include <iostream>

using namespace std;
int main (void) {



int n;
cin >> n;
int a[n], b[n], c[n];

for (int i=0; i<=n; i++){
    cin >> a[i];
    cin >> b[i];
    cin >> c[i];

    if ((a[i] > b[i] && a[i] < c[i]) || (a[i] < b[i] && a[i] > b[i])){
        cout << a[i] << " ";
}
    else if ((b[i] > a[i] && b[i] < c[i])|| (b[i] < a[i] && b[i] > c[i])){
        cout << b[i] << " ";
    }
    else if ((c[i] > a[i] && c[i] < b[i])|| (c[i] < a[i] && c[i] > b[i])){
        cout << c[i] << " ";
    }
}




 return 0;
}
Quandray     2016-11-21 15:41:43
User avatar

Hi,

You can't make the code private in a post, but people who have solved the problem are able to see your unsuccessful solutions.

1) if n=6, the code "for(int i=0;i<=n;i++){" will loop 7 times from i=0 to i=6. That probably isn't what you want.

2) There is no need to have a, b & c as arrays. You can remove every "[n]" and "[i]" from your code.

3) After your last "else if" try adding an else to handle things missed by the previous ifs. Maybe it could say

else cout << "(Oops) ";

or print the values of a, b & c inside ().

4) Try your code with this input

1
2 3 1
mattdiflorio     2016-11-21 16:18:17

Thanks a heap!

I realise where I went wrong. :)

big madik     2023-04-06 12:31:56

print("Menentukkan media dari 3 bilangan") d = int(input("masukkann ke 1 = ")) e = int(input("masukkann ke 2 = ")) f = int(input("masukkann ke 3 = "))

if (d >= e and d <= f) or (d <= e and d >= f): print (d) elif (e >= d and e <= f) or (e <= and d >= f): print (e) else: print (f)

Please login and solve 5 problems to be able to post at forum