-1
public class MyClass {
    public static void main(String args[]) {
        int n,h,w,i;
        double t;
        h = 40;
        w = 5;
        i = 2;
        t = 0.22;
        n=(h*w-i)-t*(h*w-i);
        System.out.println(n);
    }
}

On line 13 it says"/MyClass.java:9: error: incompatible types: possible lossy conversion from double to int n=(hw-i)-t(h*w-i);", What does it mean by that, and how do I fix it?

  • `n` is defined as an integer, but your math operation could produce results that would flow outside of this integer, it's telling you that precision will be lost when casting to an integer. To fix, declare `n` as a `double` – tymeJV Mar 12 '19 at 20:36
  • OOOO, thank you so much, you see im just a grade ten newbie – Anonymous Mar 12 '19 at 20:46
  • Well then you know much more than I did when I was in grade 10, keep it up, ask questions when necessary, you'll learn quick :_ – tymeJV Mar 12 '19 at 20:48
  • @Anonymous Tip: when asking a question on SO, your question will get better visibility by knowledgeable people if you tag with the language. In this case, I'm guessing you're using Java, and have tagged it as such. –  Mar 12 '19 at 20:52

1 Answers1

0

What does it mean: by having t being a double, the expression (h*w-i)-t*(h*w-i) returns a double (154.44). Yet with n being an int, you try to assign a double value to an int variable. This causes the error as this cast is not done by Java implicitly as it would be lossy (called a Narrowing Primitive Conversion in the specification: https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html). "A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range." Means: you would loose the information about the decimals.

How to deal with it: it depends on the desired outcome: - Do you want a double return value => make n a double variable - Do you want an int return value => cast (h*w-i)-t*(h*w-i) to int. Either bei forcing it to int: n=(int)(…). Or make it more transparent by explicitly by using (int)Math.round()/.floor()/.ceil() (https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html)

Locked
  • 186
  • 13