计算总是等于0

时间:2015-09-16 20:27:46

标签: android int double calculator

我有这段代码,每当我输入任何值时,结果总是变为0.我在每个if语句中设置断点,并且计算中使用的值始终有效,但是仍然有限制 值得注意的是soilDepthrnv是整数。为了以防万一,我尝试将它们转换为双打,没有任何改变。

final TextView limingTV = (TextView) findViewById(R.id.limingText);

double liming;

if (targetPh == 6.8) {
    liming = (71.4 - 1.03 * bufferpH * 10) * (soilDepth / 8) * (65 / rnv);
} else if (targetPh == 6.5) {
    liming = (60.4 - .87 * bufferpH * 10) * (soilDepth / 8) * (65 / rnv);
} else if (targetPh == 6.0) {
    liming = (49.3 - .71 * bufferpH * 10) * (soilDepth / 8) * (65 / rnv);
} else { //If 6.8 is left as default on drop down menu its not passed
    liming = (71.4 - 1.03 * bufferpH * 10) * (soilDepth / 8) * (65 / rnv);
}

limingTV.setText(String.format("%.4f lbs/acre", liming));

3 个答案:

答案 0 :(得分:3)

整数除法可以导致0值。

尝试类似 -

double result = ((double)x) / y;

您需要将soilDepth和rnv中的一个或两个转换为双精度。

要添加更多内容,您还可以尝试此操作(无需投射)

double result = x * 1.0/y;

答案 1 :(得分:2)

就像Bhush_Techidiot说的那样,在数学开始之前投两遍。带有整数的div并不像你期望的那样工作。

  final TextView limingTV = (TextView) findViewById(R.id.limingText);

  double liming;
  double dblSoilDepth = (double) soilDepth;
  double dblRnv = (double) rnv;

  if (targetPh == 6.8) {
      liming = (71.4 - 1.03 * bufferpH * 10) * (dblSoilDepth / 8) * (65 / dblRnv);
  } else if (targetPh == 6.5) {
      liming = (60.4 - .87 * bufferpH * 10) * (dblSoilDepth / 8) * (65 / dblRnv);
  } else if (targetPh == 6.0) {
    liming = (49.3 - .71 * bufferpH * 10) * (dblSoilDepth / 8) * (65 / dblRnv);
  } else { //If 6.8 is left as default on drop down menu its not passed
    liming = (71.4 - 1.03 * bufferpH * 10) * (dblSoilDepth / 8) * (65 / dblRnv);
  }

  limingTV.setText(String.format("%.4f lbs/acre", liming));

答案 2 :(得分:0)

在计算结果之前,请尝试将int转换为double

double newSoilDepth = (double) soilDepth;
double newRnv = (double) rnv;

然后在计算中使用新的双打。这可以导致更清晰的代码。