Hello. I've run into a strange problem that I can't figure out. It involves a while loop that sometimes loops one too
many times for some unknown reason. A simplified version of my code is included below:
Code:
void MyFunction(float StartTime, float TimeStep, float Interval)
{
do
{
StartTime = MyLoop(StartTime,TimeStep,Interval);
} while(StartTime<5);
return
}
float MyLoop(float StartTime, float TimeStep, float Interval)
{
short n=0;
if(StartTime==0){n=1;}else{n=0;}
[COLOR=red]while(t<StartTime+Interval+TimeStep*n)[/color]
{
DoSomethingFunction();
t+=TimeStep;
}
return t;
}
I call MyFunction with the initial values: StartTime = 0, TimeStep = 0.1, and Interval = 1. When I run it, MyLoop runs through a while loop,
incrementing the variable t by 0.1 from a starting value of 0 up to 1, and then exits the loop. Then MyFunction calls MyLoop again which again
increments t by 0.1 from a new starting value of 1.1 up to 2, etc, etc. The problem occurs when MyFunction is called the THIRD time. Insead of
t looping from 2.1 up to 3, it loops up to 3.1. At t = 3.1, the relational operator (<) in the while expression for some reason doesn't evaluate
to false, as it should, and it loops through one extra time. This leads to the next MyLoop call starting with t = 3.2 instead of 3.1!?!?!?!?
I'm thinking it's some problem with the hidden binary values of the variables, causing some slight inprecision in the variables that isn't displayed in
the C++ debugger. I can't figure it out.
Can anyone solve the mistery???
Thanks alot,
Nikolai.