Why can't I explicitly convert double to int?

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

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

You can explicitly convert double to int: int x = (int) 5.0;

Why can't you implicitly convert double to int? :int x = 5.0;

+4
source share
4 answers

The range is doublewider than int. That is why you need an explicit narthex. For the same reason, you cannot implicitly drop from longto int:

long l = 234;
int x = l; // error
+16
source

, , . integer double integer long. double integer .

Console.WriteLine ((int)5.5);  
// Output > 5

Microsoft . .NET , , , .

. , .

> MSDN

+16

# Java, intlongfloatdouble , , , . , , , , long l = getSomeValue(); float f=l; double d=f;, , l d; .

, , , , float a double , (float,float) (double,double), . , : int long , float double, float, double .

# .NET Java, long -to- float long -to- double; , "" , , , .NET Framework float double Decimal, Decimal . , long , float, double Decimal, long, , float.

, , , , , (, double) (, int) . , , 2.9999999999994, 2, 3. , , , , .

+4

, :

double x = pi/6;
double y = sin(x);

y 0,5. , x :

int x = pi/6;
double y = sin(x);

In this case, x will be truncated to 0, and then sin (0) will be accepted, i.e. y = 0.

This is the main reason why implicit conversion from double to int is not implemented in many strong type languages.

Converting an int to double actually increases the amount of information in the type and can thus always be performed safely.

+3
source

All Articles