# Problem with if ... else if

I’m experiencing some ‘weirdness’ in the use of ‘else if’ when the if tests for a ‘<’ (less than) condition. The following code shows the problem.
The printout via the serial monitor should be:
3.90 3.90
4.00 4.00
4.10 0.10
Whereas when the conditional test is ‘else if (I < 4.1)’ the printout is:
3.90 3.90
4.00 4.00
4.10 4.10

Following is the code used to generate the printout. I thought I may be experiencing the problem because the for loop variable is a float, so the second part of the sketch looks at the possibility that the incrementing of the for loop variable may be the cause of the problem. It doesn’t appear to be. I apologize in advance if I’ve been very stupid.

void setup()
{
Serial.begin(115200);
}
void loop()
{
float ts;

for (float I = 1; I <= 5; I+=0.1)
{
if ( I < 4.0)
{
ts = I;
}
else if (I == 4.0)
{
ts = I;
}
else
{
ts = I - 4.0;
}
Serial.print(I);
Serial.print("\t");
Serial.println(ts);
}
Serial.println(“");
for (float I = 1; I <= 5; I+=0.1)
{
if ( I < 4.0)
{
ts = I;
}
else if (I < 4.1)
{
ts = I;
}
else
{
ts = I - 4.0;
}
Serial.print(I);
Serial.print("\t");
Serial.println(ts);
}
Serial.println("
”);
Serial.println("**********************************");

for (float I = 1; I <= 5; I=I+0.1)
{
if ( I < 4.0)
{
ts = I;
}
else if (I == 4.0)
{
ts = I;
}
else
{
ts = I - 4.0;
}
Serial.print(I);
Serial.print("\t");
Serial.println(ts);
}
Serial.println("**********************************");
for (float I = 1; I <= 5; I=I+0.1)
{
if ( I < 4.0)
{
ts = I;
}
else if (I < 4.1)
{
ts = I;
}
else
{
ts = I - 4.0;
}
Serial.print(I);
Serial.print("\t");
Serial.println(ts);
}
while (1 == 1) {}
}

please use code tags, it is the # button

that said, comparing floats with an exact value is seldom possible as floats cannot be represented exactly. You must compare floats ALWAYS with inequalities.

have a look at this code

``````void setup()
{
Serial.begin(115200);

float ts = 0.0

for (float f = 1; f <= 5; f += 0.1)
{
if ( f < 4.0)
{
ts = f * 3;   // just to see the diff with 2nd branch
}
else if (f >= 4.0 && f < 4.005)   // between a value and a value + half stepsize
{
ts = f;  // same
}
else
{
ts = f - 4.0;
}

Serial.print(f, 4);  // 4 decimals
Serial.print("\t");
Serial.println(ts, 4);
}
}

void loop()
{
}
``````

Thank you. I knew that there was a good probability that I was being stupid :(. But I was stumped. It cost me a half day of debugging my code and losing some more hair off my head.

I appreciate the response.