Simple division [duplicate]
I must be doing something dumb:
float ans = (i/3);
So why when i = 7
is ans coming out at 2.0?
i
is an int
It's because the / operator is performing an integer division if both operands are integers. You could do this:
float ans = (i / 3.0f);
You need to make one of the operands a float, otherwise the calculation is done with integers first (which always results in an integer), before converting the result to a float.
float ans = ((float) i) / 3;
It's doing integer division because i
is an int
and 3
is an int
. Try this:
float ans = ((float)i/3.0f);
use float ans = (i / 3.0)
or float ans = (i / 3f)
or float ans = ((float)i / 3)
. /
does an integer division if both sides are of type integer.
Very simple: in C#, int / int = int.
What you're looking for is:
float ans = ((float)i/3);
Otherwise you're taking two integers and dividing them to find the number of whole times the divisor goes in to the dividend. (As mentioned, an int/int=int regardless of the destination type. And, to the compiler, "3" is another integer (unless you specify it as 3.0f
))
I am assuming that you have this in a loop of some sort. You could specify your i variable as a float instead.
for (float i = 0; i < 10; i++)
{
float ans = (i/3);
// statements
}
Just another solution.
精彩评论