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: - 感谢您指点。 –