【问题标题】:Problem with a simple code using the Math class使用 Math 类的简单代码的问题
【发布时间】:2021-02-08 00:54:01
【问题描述】:

所以我已经尝试了所有方法,但由于某种原因,我的 JAVA 程序根本无法编译。我认为我使用的数学方法的数据类型有问题。这是代码

public static int getOuthaul(int manganous, int nakir) {
    if (manganous > nakir) {
        double tmp = Math.sqrt(Math.abs(manganous - nakir));
        return Math.round(tmp);
    }
}

我非常需要一个回答的人。这意味着很多! 谢谢

这是全班:

public class Vijao {
    public static int getOuthaul(int manganous, int nakir) {
        if (manganous > nakir) {
            double tmp = Math.sqrt(Math.abs(manganous - nakir));
            float mpp = (float)tmp;
            return Math.round(tmp);
        } else {
            return Math.abs(manganous - nakir);
        }
    }

    public static int getUnhulled(int toilfully, int corse, int outwrench) {
        int wilbur = corse + 16 * toilfully;
        if (wilbur * wilbur > outwrench)
            return wilbur;
        else {
            return wilbur * (-1);
        
    }
}

这就是错误

错误:不兼容的类型:从 long 到 int 的可能有损转换 返回 Math.round(tmp); ^

【问题讨论】:

  • 贴出所有课程代码
  • 当这是整个方法时,您需要一个右括号并在 if 之后返回一个 .... 如果不执行 if 时该方法应该返回什么
  • 请发布您看到的确切编译错误。
  • 请与我们分享您遇到的错误。第一个问题是您要返回 Math.round 的结果,这可能是 double 但您的方法希望您返回 int
  • 请不要对我们大喊大叫!

标签: java class math types return


【解决方案1】:

函数的返回类型getOuthaulint,但您正试图返回 Math.round(tmp) which returns a long valueint 变量的大小是 4 字节,而 long 值需要保持 8 字节大小。

既然您了解了问题,您可以根据您的要求应用以下解决方案之一:

  1. 将函数的返回类型,getOuthaul改为long
  2. Math.round(tmp) 的值转换为int,即return (int) Math.round(tmp);

【讨论】:

    【解决方案2】:

    该错误是由于将变量从较高(较宽)类型更改为较窄类型造成的。例如,float 是 32 位浮点数据类型,而 int 是 32 位整数类型。这会导致可能丢失变量的值或精度。

    例如,让我们尝试将float 转换为int

    float fl = 1.10f;
    int in = fl; // throws incompatible types: possible lossy conversion from float to int
    

    这可以通过向下转换来解决。将大尺寸类型转换为小尺寸类型。

    是这样的:

    float fl = 1.10f;
    int in = (int) fl; // prints 1
    

    在您的情况下,方法getOuthaul() 的返回类型为int,但返回的是double(比int 宽)。

    虽然Math.abs() 可以返回int,但Math.sqrt() 会返回double。因此,明智的做法是选择适合您需要的类型并进行相应处理。这里我把它们改成longMath.round()的返回类型。

    public static long getOuthaul(int manganous, int nakir) {
        if (manganous > nakir) {
            double tmp = Math.sqrt(Math.abs(manganous - nakir));
            return Math.round(tmp);
        } else {
            return Math.abs(manganous - nakir);
        }
    }
    

    == 更新 ==

    如果返回类型必须是int

    public static int getOuthaul(int manganous, int nakir) {
        if (manganous > nakir) {
            double tmp = Math.sqrt(Math.abs(manganous - nakir));
            return Math.round((float)tmp); //not the cast to float
        } else {
            return Math.abs(manganous - nakir);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-13
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多