PDA

View Full Version : float



mickey
18th July 2006, 16:06
Do anyone have an idea of this behaviour???


cout << Density << "\n"; //this print 0.13
float f = Density*100;
slider1->setValue(f); //this set slider1 to 12!!!! why????



float f = 0.13*100;
slider1->setValue(f); //this set slider1 to 13

wysota
18th July 2006, 16:16
Probably due to limited precision of float and implicit floor casting to int.

Did you ever try to compare float values ? :)
Check this out:


#include <iostream>

int main(){
float n = 0.99;
while(n!=0.09){
std::cout << n << std::endl;
n-=0.01;
}
return 0;
}

Try this to make your app work:


float f = Density*100;
slider1->setValue((int)(0.5+f));

The second line is equivalent to
slider1->setValue(round(f)); but Windows doesn't know how to round(), so a hack like (int)(0.5+f) is needed.

Zatraz
24th July 2006, 17:45
Because in the fallow code line:


float f = Density*100;

and


float f = 0.13*100;

the number "100" in implicity cast to a float and this conversion could lead to a precision lost.

Try to use:


float f = Density*100.0;

and


float f = 0.13*100.0;

mickey
25th July 2006, 10:43
Because in the fallow code line:


float f = Density*100;

and


float f = 0.13*100;

the number "100" in implicity cast to a float and this conversion could lead to a precision lost.

Try to use:


float f = Density*100.0;

and


float f = 0.13*100.0;
sorry but your example doesn't solve the problem......

wysota
25th July 2006, 11:16
Try mine, it should work just fine.

mickey
25th July 2006, 11:52
Try mine, it should work just fine.
yes I just use it! I thanked you for this......