-3

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);
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
Jess
  • 11
  • 4

3 Answers3

1
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.

Community
  • 1
  • 1
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
0

When you do

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

You are trying to add a double (secondarray[1]) and an int (firstarray[0]), and convert the result to an int. This could lose precision, because the decimal part of the double value will be removed by rounding down. This is what the compiler is warning you about.

To indicate that you're happy with it, you can write:

int totalarays = firstarray[0] + (int)secondarray[1];

This is explicitly converting the double value to an int, by means of a cast.

js441
  • 1,134
  • 8
  • 16
0

This should work.

int totalarrays = firstarray[0] + Int32.Parse(secondarray[1].ToString());
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
FreeMan
  • 1,417
  • 14
  • 20