М. Тэмүүлэн М. Тэмүүлэн - 1 month ago 17
C Question

How to get float by integer / integer C lang

I wanna get 1.666667 by dividing 2*n+1 by 3 (n=2). and it always creates 1.000000 but i want 1.666667. I tried printing (2*n+1)/3 as a float but it doesn't work.

Answer

You are doing integer division and then assigning to a float.

Use

(2.0*n+1)/3

The 2.0 is a double and the whole expression is then converted to a double, which is assigned to a float giving you the result intended.