java - Java 中的简单数学/转换错误我一直在想念?

标签 java loops math floating-point

所以我花了三个小时试图解决下面的问题。我的逻辑似乎是正确的,我的语法似乎是正确的,但由于某种原因,代码就是不听我的。多么典型。

        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

Source of the Example

关于java - Java 中的简单数学/转换错误我一直在想念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25881008/

相关文章:

python - 查找更改整数以匹配列表中其他整数的最小移动次数

c++ - 给定一个三角形和一个线段,找到可以创建相似三角形的第三个点

java - 致命异常: Thread-5 ,空指针Object.getClass()

python - 根据另一个 df 中的值填充新的 pandas df

javascript - 有没有办法在 HAML 的 :javascript region? 中使用 Ruby 循环

arrays - 如何计算半随机整数数组中的 "expected"反转次数?

perl - 在 Perl 中将 1 添加到二进制字符串的最简单方法是什么?

java - session 超时

java - Wicket:如何向表行添加单击事件处理程序?

java - 显示时对Listview的每一项进行动画处理