【问题标题】:Incompatible types: possible lossy conversion from double to int [duplicate]不兼容的类型:从 double 到 int 的可能有损转换 [重复]
【发布时间】:2015-03-20 18:37:07
【问题描述】:

帮助?我不知道为什么我会收到这个错误。我在第 39 行:

term[1] = differentiate(Coeff[1], exponent[1]);

我该如何解决这个问题?

完整代码清单:

public class Calcprog {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int numTerms = 7;
        double[] Coeff = new double[6];
        double[] exponent = new double[6];
        String[] term = new String[6];

        System.out.println("Enter the number of terms in your polynomial:");
        numTerms = input.nextInt();

        while (numTerms > 6) {
            if (numTerms > 6) {
                System.out.println("Please limit the number of terms to six.");
                System.out.println("Enter the number of terms in your polynomial:");
                numTerms = input.nextInt();
            }
        }

        for (int i = 1; i < numTerms + 1; i++) {
            System.out.println("Please enter the coefficient of term #" + i + " in decimal form:");
            Coeff[i] = input.nextDouble();
            System.out.println("Please enter the exponent of term #" + i + " in decimal form:");
            exponent[i] = input.nextDouble();
        }
        term[1] = differentiate(Coeff[1], exponent[1]);
    }

    public String differentiate(int co, int exp) {
        double newco, newexp;
        String derivative;
        newexp = exp - 1;
        newco = co * exp;
        derivative = Double.toString(newco) + "x" + Double.toString(newexp);
        return derivative;
    }
}

【问题讨论】:

  • 你遇到了什么错误?
  • 不兼容的类型:从 double 到 int 的可能有损转换

标签: java


【解决方案1】:

您正在尝试将双参数传递给接受整数的方法,这需要进行可能导致信息丢失的强制转换。

您可以通过显式强制转换使其工作:

term[1] = differentiate((int)Coeff[1], (int)exponent[1]);

或者您可以更改您的 differentiate 方法以接受双参数,这可能更有意义:

public String differentiate(double co, double exp)

【讨论】:

    【解决方案2】:

    你的方法不是静态的,你在 main 中调用是静态的,记住非静态方法可以在静态方法中直接访问,你必须创建类的实例才能访问该方法,并且您传递的参数是double 而不是int。你的方法应该是这样public static String differentiate(double co, double exp){

    【讨论】:

      【解决方案3】:

      将 distinct 方法的参数类型更改为 double。这应该如下所示

        public String differentiate(double co, double exp){
          ...
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-21
        • 1970-01-01
        相关资源
        最近更新 更多