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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

round

Status
Not open for further replies.

filipe26

Programmer
Mar 17, 2003
152
PT
hi i have an application written in c.What i want to do is :
if (dinheiro[0]==valor || dinheiro[1]==valor)
printf("\n->Maquina %d",i+1);

dinheiro and valor are float values and when have the same value dont enter in printf.
 
And what are the problem???

As i understand you will NOT print out when dinheiro = valor?

if((dinheiro[0] != valor) || (dinheiro[1] != valor))
printf("\n->Maquina %d",i+1);

this means: if dinheiro[0] is NOT equal to valor OR dinheiro[1] is NOT equal to valor THEN do printf(...)

Totte
 
By the way, to compare float values for equality might be less effective, a better way is to get the difference and determine if the difference is below a certain value which then is called equal.

This is usable when you're calculating the values with math and will catch "rounding"-errors.

Ex: FloatDiff = Float1 > Float2 ? Float1 - Float2 : Float2 - Float1;

This means:
IF Float1 IS LARGER THAN Float2
THEN set FloatDiff to (Float1 - Float2)
ELSE set FloatDiff to (Float2 - Float1)

FloatDiff will now hold the difference and now you can decide if it's low enough to call equal or not.

Totte
 
and how i round a float value.For example i have 123.699992
i want to put in a variable the value 123.70
 
You could multiply the floating point number by the number of decimal points you want (* 10), add .5, put the float to an integer, take it back to a float, then divide by the same number you multiplied it with.

Code:
float Number = 123.699992;
float NewNumber = Number * 20; // If you want to 2 decimal places
// NewNumber = 12369.9992...
NewNumber += .5; // NewNumber = 12370.4992...
int IntNumber = (int)NewNumber; // IntNumber = 12370
Number = (float)NewNumber); // Number = 12370
Number = Number / 20; // Number = 123.70

I'm doing this off the top of my head so it may be buggy. I'll leave it up to you to clean it up. I kept the steps separate to make it easier to see.

The problem stems from how most CPUs handle floating point.

James P. Cottingham

There's no place like 127.0.0.1.
There's no place like 127.0.0.1.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top