# Casting int to float type to do average

Hi,

I want to do an average and this is my code:

``````int pulse_R, pulse_L;

float average_speed = (pulse_L + pulse_R) * 1.0 / 2;
``````

I'm hoping that it's correct? I did some research and i found that the '1.0' is needed instead of just '1' to convert to float type. But i did not include a decimal for the '2' as i assume that it doesn't matter?

But then i remember Casting, and maybe this can be simplified or written in a better way, like this:

``````float average_speed = (float)(pulse_L + pulse_R) / 2;
``````

Is this a better approach?

You could use implicit type conversion:

``````float average_speed = (pulse_L + pulse_R) / 2.0;
``````

There are two styles (in the post of OP) of codes to compute the float value of average_speed from the given 2 integer variables. We need to decide which one is relatively better; this is to answer the query of OP.

``````void setup()
{
Serial.begin(9600);

int pulse_R = 137, pulse_L = 240;
float average_speed = (pulse_L + pulse_R) * 1.0 / 2;
Serial.println(average_speed);  //188.50
//----------------------------------------
average_speed = (float)(pulse_L + pulse_R) / 2;
Serial.println(average_speed);  //188.50
//----------------------------------------
}

void loop()
{

}
``````

To me, this style : 'average_speed = (float)(pulse_L + pulse_R) / 2;' is better as it agrees with the intention of the OP. The OP has two integer variables which when averaged might give rise to a fractional value; the OP does not want to loose it. Therefore, the processing buffer should be enlarged from natural 16-bit to 'binary32' formatted 32-bit to accommodate both integer and fractional parts of the result. The result will be saved in a float type variable. So, doing the cast with the keyword float is a logical approach.