问题描述
因此,如果我有一个数字范围 '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.
除以双精度或浮点数,它会起作用:
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 ;
这篇关于为什么浮点数除以整数返回 0.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!