Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

floating point comparison

Status
Not open for further replies.

cag27

Programmer
Mar 1, 2001
9
US
Just a quick question--is there a way to do an accurate comparison of floating point numbers? Here's an excerpt of the code that I'm working on:

//this while loop will be executed if the user
//enters a negative or zero value as a check
//amount
while( *ptr < 0.01)
{
printf(&quot;Please enter a positive amount for the check: &quot;);
scanf(&quot;%f&quot;, ptr);
getchar();
} //end of while loop

Unfortunately, when '0.01' is entered, I go into the while loop. I know that 1/100 cannot be accurately represented in binary and that this must be what is causing the problem, but does anyone have any a relatively simple way to solve this problem? Thank you.

Carrie
 
have your tried something along the lines of...

char myValue[MAX_SIZE];

sprintf(myValue,&quot;%f&quot;,*ptr);

and then

while(strcmp(myValue,&quot;0.01&quot;)<0) // string 1 less

On a side note, make sure the sprintf writes it as 0.01 and not as .01 or you will run into problems.


matt
 
Yes you are right cag27, problems are there in processing the floating numbers, but you can solve this by using double precession numbers.

But in this case its different. I think the ptr is an floating point variable [ your are using %f to read it ], but while checking you used the expression (*prt < 0.01). Here you are checking a floating point number with a double number [ 0.01 is a double precession number by default, if you want to represent it as a float number then you have put 0.01f ]. While accessing a float 0.01 [0.01f] this will something less 0.01, but while using double 0.01 [ 0.01 ] this is 0.01 only.

So make this expression like (*ptr < 0.01f) this. Otherwise declare the ptr as a double variable and use the expression as it is [ while reading the double number put %g ]. These two expressions will check prefectly.

Regards
Maniraja S




 
Zyrenthian and smaniraja,
Thank you both for your suggestions--I went with the second option of just adding the 'f' to 0.01 in my while comparison, and it works great! I knew that there had to be some simple way to fix the problem, and there was! Thanks again.

Carrie
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top