Why can't I implicitly convert a double to an int?

前端 未结 5 1601
暗喜
暗喜 2021-01-19 14:20

You can implicitly convert an int to a double: double x = 5;

You can explicitly convert an int to a double: double x = (double) 5;

<
5条回答
  •  攒了一身酷
    2021-01-19 14:34

    WHEN YOU CONVERT FROM DOUBLE TO INT IMPLICITLY then you are trying to store a no. with large memory into a variable having small memory(downcasting)

    double d=4.5;

    int x=d;//error or warning

    which can be dangerous as you may lose out the information like you may lose the fractional part of a double while storing it in an integer

    whereas that is not the case while storing an int value in a double variable(upcasting).

    int x=2;

    double d=x; //correct

    so the compiler doesn't allows to implicitly convert from double to int( or storing double value in an int) because someone might do it unknowingly and expect no loss of data. But if you explicitly cast it means that you say to compiler that cast whatever be the danger ,no matter ,i will manage....hope it helps..

提交回复
热议问题