# float calculations

Hello, from a beginner :) :)

I am very new to Arduino and C programming, and trying to find my way through it. Slowly and by reading and trial and error I am learning, so please bear with me...

While I was trying to work with some floats, I noticed that a code such as

float var; var=3/4; Serial.println(var,4);

returns 0.0000

but if you do float var; var=(float) 3/4; Serial.println(var,4);

then it returns 0.7500 (as desired)

Can someone help me understand why is this, and is this (casting) the correct way to use floats?

Much appreciated;

Try var = 3/4.0; to force the calculation to be done as a float rather than integer which is the default.

For integer division, 3/4 is zero, with a remainder of 3.

Wow, that was fast!

So if I understand this correctly, default calculations happen as int type even though the destination variable is float.

good to know.

Wow, that was fast!

Unless you tell it differently, the default math operations assume int data types. As Bob pointed out, using a decimal point on numeric constants tells the compiler to use floating point math. As you might guess, all of these forms produce the same result:

``````void setup() {

float var;

Serial.begin(9600);

var = 3.0 / 4;
Serial.println(var,4);

var = 3.0 / 4.0;
Serial.println(var,4);

var = 3 /(float) 4;
Serial.println(var,4);

var = (float) 3 / 4;
Serial.println(var,4);

var = (float) 3 / (float) 4;
Serial.println(var,4);

}

void loop() {

}
``````

They work properly because all of them nudge the compiler in the right direction for the math operation.