所以我花了三个小时试图解决下面的问题。我的逻辑似乎是正确的,我的语法似乎是正确的,但由于某种原因,代码就是不听我的。多么典型。
float counter = 0;
float pColor = counter / ((float)Math.abs((x_end - x_start)));
System.out.println("FIRST EVER PCOUNTER:" + pColor);
System.out.println("FIRST EVER X START IS: " + x_start);
System.out.println("FIRST EVER X END IS: " + x_end);
System.out.println(x_end + " " + x_start);
// part of another program
while(x != x_end){
x+= step_x;
counter++;
System.out.println("Count is:" + counter);
if(p<0){
p+= twoDy;
}
else{
y += step_y;
p += twoDyMinusDx;
}
System.out.println("pColor is: "+pColor);
System.out.println("p1.c.r: "+ p1.c.r);
System.out.println("x_end is: " + x_end);
System.out.println("x_start is:" + x_start);
System.out.println("");
所以上面所有的打印语句都是为了检查pColor是否正在改变。由于某种原因,所有打印语句都说 pColor 为 0.0
FIRST EVER PCOUNTER:0.0
FIRST EVER X START IS: 341
FIRST EVER X END IS: 350
350 341
Count is:1.0
pColor is: 0.0
p1.c.r: 1.0
x_end is: 350
x_start is:341
Count is:2.0
pColor is: 0.0
p1.c.r: 1.0
x_end is: 350
x_start is:341
Count is:3.0
pColor is: 0.0
p1.c.r: 1.0
x_end is: 350
x_start is:341
Count is:4.0
pColor is: 0.0
p1.c.r: 1.0
x_end is: 350
x_start is:341
Count is:5.0
pColor is: 0.0
p1.c.r: 1.0
x_end is: 350
x_start is:341
Count is:6.0
pColor is: 0.0
p1.c.r: 1.0
x_end is: 350
x_start is:341
Count is:7.0
pColor is: 0.0
p1.c.r: 1.0
x_end is: 350
x_start is:341
Count is:8.0
pColor is: 0.0
p1.c.r: 1.0
x_end is: 350
x_start is:341
Count is:9.0
pColor is: 0.0
p1.c.r: 1.0
x_end is: 350
x_start is:341
如您所见,计数器不断增加,但每个 pColor 仍保持在 0.0。这是什么问题?
最佳答案
这里
float counter = 0;
float pColor = counter / ((float)Math.abs((x_end - x_start)));
pColor
的结果始终为 0.0,因为 0 除以任何数字都会得到零。
例如:
System.out.println( 0 / 1);
输出:
0
另一个例子:
0 divided by any number is 0. This result is explained by the fact that no number, even 0, can go into 0. In the example below 9 cannot go into 0 at all, resulting in the 0 answer.
Example: 0 / 9 = 0
关于java - Java 中的简单数学/转换错误我一直在想念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25881008/