![](/img/trans.png)
[英]Why does this output 0.0 0.0 0.0 0.0 rather than the execute method's return calculations?
[英]Why does dividing a float by an integer return 0.0?
因此,如果我有一個數字范圍'0 - 1024'並且我想將它們帶入'0 - 255',則數學將要求將輸入除以輸入的最大值(在這種情況下為1024),這將給出我是一個介於0.0 - 1.0之間的數字。 然后乘以目標范圍,(255)。
這就是我想要做的!
但由於某種原因,在Java中(使用Processing)它總是返回值0。
代碼就像這樣簡單
float scale;
scale = (n/1024) * 255;
但我得到0.0。 我試過double和int。 一切都無濟於事。 為什么!?
這是因為你正在進行整數除法。
除以double或float,它將起作用:
double scale = ( n / 1024.0 ) * 255 ;
或者,如果你想把它當作浮子,
float scale = ( n / 1024.0f ) * 255 ;
n / 1024是整數除法 ,它產生一個整數(在這種情況下為0)。
請改用n / 1024.0
。
我認為n
是一個int
。 因為常量1024和255都是int
所有右側計算都是用整數運算完成的。 這意味着在乘以255
之前, n/1024
的結果將被截斷為整數值。
任何這些修改都將使計算正常工作:
scale = n / 1024.0 * 255.0; // Use double constants.
scale = (double) n / 1024 * 255; // Convert n to a double.
scale = n * 255 / 1024; // Multiply before dividing.
最后一個仍然使用整數數學但是切換操作的順序意味着你不會得到不希望的截斷為0.你仍然只會獲得整數答案,所以你將丟失答案中的任何小數點。
你應該通過乘法FIRST將n自動轉換為float,否則你正在進行整數運算然后轉換結果,而不是在浮點數之間進行操作。
float scale;
scale = n * 1.0 / 1024 * 255;
在你的情況下,當你進行整數除法時, n/1024
得到0。 為了克服這個問題,你可以將n
為float
。 接下來,您將得到0.0
到1.0
之間的結果,然后乘以255
並將結果轉換回整數。 您還需要將scale
聲明為int
int scale;
int n = 80;
scale = (int)(((float)n/1024) * 255);
其他人已經給出了很好的答案。 如果你希望你的比例是一個整數(如果你的n已經是一個整數就有意義),你可以做到
int scale = ((255 * n)/1024);
請注意,只要這些是數字,就不會遇到任何問題,因為當最大n = 1024時,n * 255總是適合int。
會更靈活
int scale(int value, int old_max, int new_max){
java.math.BigInteger big_value = java.math.BigInteger.valueOf(value);
java.math.BigInteger big_old_max = java.math.BigInteger.valueOf(old_max);
java.math.BigInteger big_new_max = java.math.BigInteger.valueOf(new_max);
java.math.BigInteger mult = big_value.multiply(big_old_max);
return (int) mult.devide(big_new_max).doubleValue();
}
盡管我承認這有點冗長,但你不會以這種方式溢出任何一個
編輯:
基本相同,但不那么笨重(雖然對於非常高的數字,你可能會遇到一些精確的錯誤)
int scale(int value, int old_max, int new_max){
double factor = (double) new_max / (double) old_max;
return factor * value;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.