Simple separation

I have to do something dumb:

float ans = (i/3);

So why, when i = 7is ans coming out in 2.0?

i is int

+5
source share
7 answers

This is because / operator performs integer division if both operands are integers. You can do it:

float ans = (i / 3.0f);
+11
source

You need to make one of the operands float, otherwise the calculation is performed with integers first (which always leads to an integer) before converting the result to float.

float ans = ((float) i) / 3;
+6
source

, i int 3 int. :

float ans = ((float)i/3.0f);
0

float ans = (i / 3.0) float ans = (i / 3f) float ans = ((float)i / 3). / , .

0

Very simple: in C #, int / int = int.

0
source

What are you looking for:

float ans = ((float)i/3);

Otherwise, you take two integers and dividing them to find the number of integer times when the divisor goes to the dividend. (As already mentioned, int / int = int regardless of the type of destination. And for the compiler, “3” is a different integer (unless you specify it as 3.0f))

0
source

I guess you have this in some kind of loop. Instead, you can specify your i variable as a float.

for (float i = 0; i < 10; i++)
{
   float ans = (i/3);
   // statements
}

Another solution.

0
source

All Articles