为什么这个整数结果不如预期?

时间:2012-03-10 16:07:27

标签: java math

我有7个整数和一个计算。计算maximumY应该等于-3940,而是生成1724869434

为什么会这样?

in1 = 1000;
in2 = 1000;
in3 = 100;
in4 = 100;
in5 = 100;
in6 = 1000;
in7 = 100;
duration / 1000 = 24;
frequency1 / 1000 = 5
frequency2 / 1000 = 5
frequency3 / 1000 = 10
frequency4 / 1000 = 24
frequency5 / 1000 = 2
frequency6 / 1000 = 2
frequency7 / 1000 = 4

int cal1 = in1 + (in1 * (duration / 1000) / (frequency6 / 1000));
int cal2 = in1 + (in2 * (duration / 1000) / (frequency7 / 1000));
int cal3 = out1 +(out1 * (duration / 1000) / (frequency1 / 1000));
int cal4 = out2 +(out2 * (duration / 1000) / (frequency2 / 1000));
int cal5 = out3 +(out3 * (duration / 1000) / (frequency3 / 1000));
int cal6 = out4 +(out4 * (duration / 1000) / (frequency4 / 1000));
int cal7 = out5 +(out5 * (duration / 1000) / (frequency5 / 1000));

maximumY = (cal1) + (cal2) - (cal3) - (cal4) - (cal5) - (cal6) - (cal7);

1 个答案:

答案 0 :(得分:1)

如果要执行整数运算,可以使用long

否则我会使用带有适当舍入的double或BigDecimal。

您可以简化代码

long cal6 = out4 +(out4 * (duration / 1000) / (frequency4 / 1000));

long cal6 = out4 +(out4 * 24 / (24));

long cal6 = out4 * 2;