返回非浮点值的整数参数划分

时间:2017-04-21 17:46:11

标签: c# .net floating-point type-conversion

我有两个整数参数,我将这些参数分开并将结果存储到浮点变量。

float kx=(float)(img.Width / refsize.Width);

解决问题的实例

img.width=2620 refsize.width=1499 

kx变量应该通过普通数学返回~1.747831887925284

但它会将其四舍五入为整数kx=1

为什么会这样?

4 个答案:

答案 0 :(得分:1)

float kx=(img.Width / (float)refsize.Width);

之所以发生这种情况,是因为你划分了两个整数,结果是int,你将其转为浮动

答案 1 :(得分:1)

这归结为操作顺序

float kx=(float)(img.Width / refsize.Width);

首先评估

img.Width / refsize.Width

然后将结果(即整数1)转换为浮点数。

为了获得预期的结果,在分割之前将两个宽度都转换为浮点数(技术上你可以转换任何一个,编译器将提升另一个,但我更喜欢明确。你永远不会知道谁将维护代码年路)。

float kx=(float)img.Width / (float)refsize.Width;

答案 2 :(得分:0)

这是因为您首先将整数除以整数或(DivideByZeroException)。然后将整数结果转换为float

尝试float kx = (((float)img.Width)/refsize.Width);

答案 3 :(得分:0)

由于括号具有优先权,因此您将整数除以整数,得到结果1.您应该写

float kx = (float)img.Width / (float)refsize.Width;

获得正确的结果。

相关问题