Billie
Billie

Reputation: 9146

C# - trying to cast from double to int, but failing

I try to pow a number with 2. I wrote:

int xy = y - x;
double xx = (double)xy;
distance = Math.Pow(xx, (double) 2.0);

x, y are integers.

I getting this error:

cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)

Why is that error? Both params are double typed.

The error red line drawn below this code: Math.Pow(xx, (double) 2.0);

Upvotes: 1

Views: 569

Answers (4)

Bojan Komazec
Bojan Komazec

Reputation: 9536

Why is that error?

Because Math.Pow returns double and you're trying to assign it to a variable (distance) which has int type.

When converting double precision floating point number (double type) into integer (int type) you're loosing information. That's why compiler doesn't allow implicit conversion and therefore throws that error message you posted above. In this situation you have to tell compiler you're aware of potential information loss and you do that by applying explicit casting:

int distance = (int)Math.Pow(xx, (double)2.0)

Upvotes: 2

Soner Gönül
Soner Gönül

Reputation: 98868

Try like this;

int xy = y - x;
double xx = (double)xy;
double distance = Math.Pow(xx, (double)2.0);

Because in this case Math.Pow returns double. From metadata;

public static double Pow(double x, double y);

Upvotes: 1

Tilak
Tilak

Reputation: 30728

2.0 is already Double. Seems like distance is int

 distance = (int)Math.Pow(xx, 2.0);

Upvotes: 0

I4V
I4V

Reputation: 35363

I guess distance is declared as int

 distance = (int)Math.Pow(xx, (double) 2.0);

Upvotes: 9

Related Questions