Hello all.
float val = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
val = 5 / 2;
Serial.println(val);
delay(1000);
}
I can't understand, why result is 2.00, instead 2.50 ? :-[ ![]()
Hello all.
float val = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
val = 5 / 2;
Serial.println(val);
delay(1000);
}
I can't understand, why result is 2.00, instead 2.50 ? :-[ ![]()
Because you've asked for integer division. 5 and 2 are integers! Try this:
val = 5.0 / 2.0;
Thanks. ![]()
And while reading manual, i fount another one way:
val = (float)5 / 2;
![]()
val = 5.0 / 2.0;
val = (float)5 / 2;
are more or less then same thing to the compiler. The second form tells the compiler to treat the value 5 as floating point. The compiler will always promote any other variables in an expression to a float if any one is a float. But because many Arduino users may not be aware of the promotion properties of the language, the former is easier for people to understand.