方法中的计算错误

时间:2015-08-17 12:48:19

标签: java methods

我的用户输入正常工作,而且我的加仑工作方法也正常工作但是当我尝试计算工时时,它的作用是用先前计算的结果来计算它,而不是我的计算结果指定。

这是我到目前为止所拥有的。它的作用是使用加仑的结果乘以8而不是使用用户输入的平方英尺。我似乎无法弄清楚为什么会这样做

int result=gallonsofpaint(numberofsquarefeet,115,1);
System.out.println("the number of gallons of paint required is " + result);

int resultnumberofhours = hoursoflabor(numberofsquarefeet,115,8);
System.out.println("the number of hours needed are " + resultnumberofhours);

public static int gallonsofpaint(int numberofsquarefeet, int squarefeet,int paint){
    int result = numberofsquarefeet/115*1;
    return result;
}

public static int hoursoflabor(int numberofsquarefeet, int squarefeet,int labor){
    int resultnumberofhours = numberofsquarefeet/115*8;
    return resultnumberofhours;
}

2 个答案:

答案 0 :(得分:0)

根据您在方法中定义的公式,对于特定的numberofsquarefeetresultnumberofhours始终为result乘以8.您可以通过转换字段来避免这种情况数据类型为浮点数。

答案 1 :(得分:0)

首先,返回类型为int

  

所以900/115你得到的不是7.82

其次,如果您希望结果具有小数,请切换到double或float。

import java.util.Scanner;

public class So{
    public static void main(String args[]) {
        int numberofsquarefeet = 900;
        int result=gallonsofpaint(numberofsquarefeet,115,1);
        System.out.println("the number of gallons of paint required is " + result);

        double resultnumberofhours = hoursoflabor(numberofsquarefeet,115,8);
        System.out.println("the number of hours needed are " + resultnumberofhours);
    }
    public static int gallonsofpaint(int numberofsquarefeet, int squarefeet, int paint) {
        int result = numberofsquarefeet / 115 * 1;
        return result;
    }

    public static double hoursoflabor(int numberofsquarefeet, int squarefeet, int labor) {
        double resultnumberofhours = (double)(numberofsquarefeet * 8 ) / 115;
        return resultnumberofhours;
    }
}

如果您不想在62.608中使用小数,并希望答案为62

import java.util.Scanner;

public class MaximiseSum {
    public static void main(String args[]) {
        int numberofsquarefeet = 900;
        int result=gallonsofpaint(numberofsquarefeet,115,1);
        System.out.println("the number of gallons of paint required is " + result);

        int resultnumberofhours = hoursoflabor(numberofsquarefeet,115,8);
        System.out.println("the number of hours needed are " + resultnumberofhours);
    }
    public static int gallonsofpaint(int numberofsquarefeet, int squarefeet, int paint) {
        int result = numberofsquarefeet / 115 * 1;
        return result;
    }

    public static int hoursoflabor(int numberofsquarefeet, int squarefeet, int labor) {
        int resultnumberofhours = (int) ((numberofsquarefeet * 8 ) / 115);
        return resultnumberofhours;
    }
}