I sort of see where you're trying to go with this, you're iterating with time incrementing 1 hour at a time. However, before you do it this way again, I would suggest that you can do it without using a while loop.
1 2 3 4 5
|
while(first_car<second_car)
{
time2++;
}
|
This is an infinite loop.
time2 will keep being incremented, but
first_car and
second_car are never going to be change.
My question is, do you need to use while loops? This seems more like a physics problem than a programming problem. In which case, I would prefer not to use while loops for solutions that can expressed in closed form.
Let's do the problem where they are going the same direction:
1 2 3 4 5 6 7 8
|
int A_position = 0;
int B_position = 900;
int car1_position_initial = position_A;
int car2_position_initial = position_B;
int car1_speed = 75; // A towards B, @ 75 km/h
int car2_speed = 60; // same direction, @ 60 km/h
|
Linear Motion states that:
position = speed * time
or, equivalently,
position_final = speed * time + position_initial
You have two different speeds (but same direction), and two different starting positions.
You must set the final positions equal to each other.
Your equation for Car 1 is:
position_final = 75 * time + 0
Your equation for Car 2 is:
position_final = 60 * time + 900
Set these equations equal to each other and solve for time:
75 * time + 0 = 60 * time + 900
(75 - 60) * time = 900 - 0
time = (900 - 0) / (75 - 60) = 60 hours.
The cars will meet after 60 hours.
Now you just need to plug in the appropriate variables for 75 km/h, 60 km/h, 0 km, and 900 km into your program.