Jess Jess - 1 year ago 102
C# Question

Can't find location of implicit cast

I'm trying to find the total of two given number arrays for my assignment, but I keep receiving the error:

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

int[] firstarray= new int[4] { 4, 20, 60, 150 };
double[] secondarray= new double[4] { 5, 40.5, 65.4, 145.98 };

firstarray[0] = 20;
secondarray[1] = 5;

int totalarrays = firstarray[0] + secondarray[1];
Console.WriteLine("Total of the two arrays " + totalarrays);

Answer Source
int totalarays = firstarray[0] + secondarray[1];

should be

double totalarays = firstarray[0] + secondarray[1];

An int + a double ends up in a double. If it didn't you would lose the precision of the double in the result - there is no implicit way to do that.

If you need to convert the double to an int there are many different techniques depending on your requirements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download