for(int i=0;i<100;i++)
{
float val=(i/100);
System.out.println(val);
}
0.0
0.0
0.0....
所需的輸出:
0.0
0.1
0.2
0.3...
我試圖百分比值0之間的轉換成100 爲什麼發生呢?
for(int i=0;i<100;i++)
{
float val=(i/100);
System.out.println(val);
}
0.0
0.0
0.0....
所需的輸出:
0.0
0.1
0.2
0.3...
我試圖百分比值0之間的轉換成100 爲什麼發生呢?
嘗試進行更改爲:
float val=(i/100f);
截至目前你將一個int通過返回一個int和int,因此你沒有得到想要的結果。
由於i
& 100
都是整數值,它們的除法結果也將是一個整數。因此,你需要通過,而不是他們(分裂操作數)中的至少一個轉換爲float
,&鴻溝:
for(int i=0;i<10;i++) // Change the loop step to 10 also
{
float val = (float)i/10; // or float val = i/(float)10;
System.out.println(val);
}
輸出:
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
i
和100
均爲整數,所以會返回一個整數。你將整數分開,這意味着你正在使用整數除法。
在整數除法中,結果的小數部分被丟棄。
嘗試這樣做:
float val = (i/100f);
你需要劃分float
得到float
,否則int/int
只是給出一個int
且將其分配給一個float
。
float val=(Float.valueOf(i)/100);
原因是java推廣規則。 在表達式中,(i/100)都是整數,所以結果是整數。 99/100是o.99,當轉換爲int它變爲0。
根據Java語言規範(數字小促進5.6
Numeric promotion (§5.6) brings the operands of a numeric operator to a common type so that an operation can be performed.
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:
1. If any operand is of a reference type, it is subjected to unboxing conversion
(§5.1.8).
2. Widening primitive conversion (§5.1.2) is applied to convert either or both
operands as specified by the following rules:
• If either operand is of type double, the other is converted to double.
• Otherwise, if either operand is of type float, the other is converted to float.
• Otherwise, if either operand is of type long, the other is converted to long.
• Otherwise, both operands are converted to type int.
i
的和100
的數據類型是在你的表達整數。整數除法(int/int)
計算爲Math.floor(int/int)
(相當於操作),它總是在你的情況下返回零。
使用以下expresssions的一個操作數的ATLEAST一個浮動或雙轉換嘗試。
float val=(float)i/100
或 float val=i/(float)100
或 float val=i/100.0f
你的問題是,編譯器2點的整數進行整數除法,則結果(0)轉換成一浮動。爲了避免這種情況,請在您的部門的任何一方添加明確的演員陣容。這會更早地投射並執行浮點分割。
float val = (float) i/100;
// output
0.0
0.01
0.02
0.03
...
您應該提供更多解釋 – Wouter
這是因爲你在做整數除法。
除以一個雙鍵或一個浮子,並且它將工作:
雙標度=(N/1024.0)* 255;
或者,如果你想把它當作一個浮動,
浮規模=(N/1024.0f)* 255;
或
float val =(float)i/100; //隱藏我浮動和分裂
不,你不能。您需要從double到float的顯式投射。 (i/100.0)將返回一個雙精度值。 –
@SagarGandhi: - 感謝您指點。 –