为什么将float除以整数返回0.0? [英] Why does dividing a float by an integer return 0.0?
问题描述
因此,如果我有一系列数字'0 - 1024'并且我想将它们带入'0 - 255',则数学将指示将输入除以输入的最大值(在这种情况下为1024)这将给我一个介于0.0 - 1.0之间的数字。然后乘以目的地范围,(255)。
So if I have a range of numbers '0 - 1024' and I want to bring them into '0 - 255', the maths would dictate to divide the input by the maximum the input will be (1024 in this case) which will give me a number between 0.0 - 1.0. then multiply that by the destination range, (255).
这就是我想要做的!
但由于某种原因,在Java中(使用Processing)它总是会返回0值。
But for some reason in Java (using Processing) It will always return a value of 0.
代码就像这样简单
float scale;
scale = (n/1024) * 255;
但我得到0.0。我试过double和int。一切都无济于事。为什么!?
But I just get 0.0. I've tried double and int. all to no avail. WHY!?
推荐答案
这是因为你正在进行整数除法。
It's because you're doing integer division.
除以double或float,它将起作用:
Divide by a double or a float, and it will work:
double scale = ( n / 1024.0 ) * 255 ;
或者,如果你想要它作为浮动,
Or, if you want it as a float,
float scale = ( n / 1024.0f ) * 255 ;
这篇关于为什么将float除以整数返回0.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!