[Solved] Arrival/departure program


I think the problem is the logic in this code:

v = i1;
c = u2;

if( g2 < g1 )  {
    v = i2;
    c = u2;
}  
if( g3 < g2)  {
    v = i3;
    c = u3;
}  
if( g4 < g3) {
    v = i4;
    c = u4;
}  

Consider the case g1 < g3 < g2. Here you want to select g1 but what actually happens is?

1) At first you assume g1 to be the smallest. (fine)

2) Then you compare g2 and g1 but continue with g1 as smallest (fine)

3) Then you compare g2 and g3 and selects g3as smallest !! (error)

The problem is that you never compare g3 to g1 and therefore you select g3 even though it is actually larger than g1. That’s not what you want.

What you need is an extra variable holding the current smallest. Like:

v = i1;
c = u2;
smallest = g1;

if( g2 < smallest )  {
    v = i2;
    c = u2;
    smallest = g2;
}  
if( g3 < smallest)  {
    v = i3;
    c = u3;
    smallest = g3;
}  
if( g4 < smallest) {
    v = i4;
    c = u4;
    smallest = g4;
}  

BTW: I’ll recommend that you soon learn about arrays as that will simplify your code

1

solved Arrival/departure program