无论输入是什么,操作的输出始终为零

时间:2014-09-26 11:07:02

标签: java

我有这段代码,变量s的输出始终为零:

double v = high; double s; double h;
if (v == 0) {
    s = 0;
    h = 0;
    System.out.println("v and s and h is zeroo" + v + s + h);
} else {
    s = (high - low) / high;
    System.out.println("s is equal to" + s);
    System.out.println("high is equal to" + high);
    System.out.println("low is equal to" + low);
    if (s == 0) {
        h = 0;
        System.out.println("high and low are equals" + high + "==" + low);
    } else {
        double alpha;
        alpha = 60 * (mid - low) / (high - low);
        System.out.println("alpha is : " + alpha);

    }
}

输出示例:

s is equal to0.0
high is equal to139
low is equal to30
high and low are equals139==30

4 个答案:

答案 0 :(得分:4)

由于highlow都属于int类型,因此行s = (high-low)/high中的除法使用整数除法,因为high - low总是更少比high(除非低是负数),结果总是为零。

要解决这个问题,请将其中一个加倍:

s = (high-low)/(double)high;

答案 1 :(得分:2)

仅将变量定义为double类型并不意味着操作本身将具有双精度。您的高和低分别为139和30,它们是整数且整数/整数整数,然后将其扩展为双精度(即0.0)

只需将高或低转换为double,您将获得双精度结果

 s=   (high-low)/(double)high;

答案 2 :(得分:0)

由于高和低是整数,

的结果
(high-low)/high

计算为int值。

尝试:

1.0*(high-low)/high

答案 3 :(得分:0)

这看起来像一个舍入问题。如果你想用它们执行正确的除法,则将高和低声明为双倍。