I need to use an if/else statement like the following in another program of mine, but for some reason there is a problem with it.

The statement seems to work for all values, except when I enter the N_MAX value of 0.1. It should be considered valid, but it's not. The thing that's really puzzling is that if I enter 0.001 I get valid, yet the same won't happen for 0.1.

``````#include <stdio.h>
#include <stdlib.h>
#define N_MIN 0.001
#define N_MAX 0.1

int main()
{
float num;
printf("Enter a number.\n");
scanf("%f", &num);
if(num < N_MIN || num > N_MAX)
{
printf("Invalid.\n");
}
else
{
printf("Valid.\n");
}
system("PAUSE");
return(0);
}``````
2
Contributors
1
2
Views
8 Years
Discussion Span
Last Post by Narue

>It should be considered valid, but it's not.
Direct comparison of floating-point values is risky because some values might not be exact, and the comparison will produce an unexpected result. You should take care to use a fudge factor when doing this kind of comparison:

``````#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#define N_MIN 0.001
#define N_MAX 0.1

int fltcmp ( float lhs, float rhs )
{
if ( lhs < rhs && ( rhs - lhs ) >= fabs ( rhs * FLT_EPSILON ) )
return -1;
else if ( lhs > rhs && ( lhs - rhs ) >= fabs ( lhs * FLT_EPSILON ) )
return +1;
else
return 0;
}

int main()
{
float num;
printf("Enter a number.\n");
scanf("%f", &num);
if(fltcmp(num, N_MIN) < 0 || fltcmp(num, N_MAX) > 0)
{
printf("Invalid.\n");
}
else
{
printf("Valid.\n");
}
return(0);
}``````
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.