Common mistakes with conditionalss
Comments and questions to John Rowe.
Using = not ==
|
Wrong
| Right
|
if ( a = b )
|
if ( a == b)
|
The expression on the left set a to equal b, the
one on the right tests to see if a equals b.
|
Using a == b == c or a >b > c
|
Wrong
| Right
|
if (a == b == c)
|
if ( a == b && b == c )
|
if ( a > b > c )
|
if ( a > b && b > c )
|
|
Wrong
| Right
|
if ( x > 100 )
printf("x is greater than 100\n");
if ( x > 10 )
printf("x is greater than 10 but less then or equal to 100\n");
if ( x > 0 )
printf("x is greater than 0 but less then or equal to 10\n");
else
printf("x is zero or negative\n");
Step through this code
|
if ( a != b) {
c = c/(a-b);
}
|
|
Rounding errors mean that two floating-point expressions
are unlikely to be equal even when mathematically they ought to be. Instead
we use fabs() of the difference. Note fabs()
not abs() which is the integer function.
|
Wrong
| Right
|
if ( x*x == 2.0 )
|
if (fabs(x*x - 2.0) < 1e-6)
|
Using abs() not fabs()
Remember that abs() is the integer
so any floating-point expression whose absolute
value is less than one will become zero.
|
if (abs(x*x - 2.0) < 1e-6)
printf("Should have used fabs()!\n");
|
if (fabs(x*x - 2.0) < 1e-6)
// (This is the same as the previous example.)
|
Longer example of comparing floating-point numbers for equality
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
double x;
x = sqrt(2.0);
if ( x*x == 2.0 ) printf("x*x is exactly 2\n");
else
printf("x*x - 2 is %g\n", x*x - 2.0);
if (fabs(x*x - 2.0) < 1e-6) printf("Close enough!\n");
x = x + 0.1;
if (abs(x*x - 2.0) < 1e-6)
printf("Should have used fabs()!\n");
return 0;
}
Step through this code
|