简体   繁体   English

在简单的数学计算中始终获得0值

[英]Get always 0 value in a simple mathematical calc

I'm testing an app that use this method 我正在测试使用此方法的应用

public double range(double[] myArray1, double[] myArray2, double[] myArray3) {
    int count=myArray1.length;

    double dfw = (3 * count) - 3;
    double msw = totalval / dfw;
    double critical = (2 / count) * (msw / 2);

    double range = Math.sqrt(critical);
    double crange = 3.95* range;

    return critical;
}

I have tried to print all values for an input of 3 arrays all with length 4; 我试过打印长度为4的3个数组的输入的所有值。

dfw=9
msw=341.6388888888889
critical=0;
range=0;
crange=0;

All values are calculated correctly but when the execution reach critical , the values aren't calculated. 所有值均已正确计算,但是当执行达到critical值时,不会计算这些值。

How is this thing possible? 这怎么可能? Why critical results always 0 causing a wrong output? 为什么critical结果始终为0导致错误输出?

The problem is that (2 / count) is an Integer operation, which will return 0 if count > 2 . 问题在于(2 / count)是一个Integer运算,如果count > 2 ,它将返回0

To change it to a floating point operation, you can use a floating point literal, like this: 要将其更改为浮点运算,可以使用浮点文字,如下所示:

double critical = (2.0 / count) * (msw / 2);

you are performing integer math. 您正在执行整数数学。 int myvalue = 1/2 will give you myvalue = 0; int myvalue = 1/2将给你myvalue = 0;

you can perform a cast 你可以表演

double critical = (2.0 / (double)count) * (msw / 2.0);

to promote count from int to double countint提升到double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM