 # Quick question on float variable

Hello friends

``````unsigned long X = 1001;
unsigned long Y = 1000;
unsigned long T;
float Z;

Z = X/Y;
T = (14 / Z) * 60;
``````

If I want to see the result as follows:

Z = 1.001 T = 839

I need Z has 3 digits after decimal point and T is a rounded number. How would I define them variable? Any idea?

Thanks, BTFdev

I need Z has 3 digits after decimal point

Not possible. You can format the display so that you only see three decimal places, but there is no way to limit a float to having just three decimal places of accuracy. Save yourself a lot of grief and don't even go there.

``````T = (14 / Z) * 60;
``````

Mixing float and int arithmetic will have you back here asking why this doesn't work. Learn right from the beginning to do it right.

14 is an int. 14.0 is a float. 60 is an int. 60.0 is a float. Where you will store the result is completely immaterial until the value to store has been computed.

Consider how this might provide different results

``````unsigned long X = 1001;
unsigned long Y = 1000;
unsigned long T;
float Z;

Z = (float)X/Y;
T = (60 * 14) / Z;
``````

Yes Morris,

I re-read the programming reference and did (float)X/(float)Y

Yes, it worked.

``````(float)X/Y;
(float)X/(float)Y;
``````

On the same note, the above two lines, are they the same?

Thanks, BTFdev

On the same note, the above two lines, are they the same?

No, they are not. The first will perform integer arithmetic, and then cast the int result to a float. The second will perform floating point arithmetic. The result will be a float.

They have the same effect.

The first line explicitly tells the compiler to promote X to float, which has the side-effect of implicitly promoting Y before the division.

The second line explicitly forces both promotions, which isn't really needed but doesn't hurt anything.

BTW - the parentheses in the assignment to T aren't really needed, and I included them only to emphasize the order of evaluation, which would be the same even if they weren't present.

@PaulS

``````#include <stdio.h>

int main(void)
{	int x = 4, y = 5;
float z = (float)x / y;
printf("%f\n",z);
return 0;
}

~/prj/fus/src/Samples: gcc floatest.c -o floatest
~/prj/fus/src/Samples: floatest
0.800000
``````

The reason is that a (cast) has higher priority than division. See C Operator Precedence Table