Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array values can't produce a double value [duplicate]

Tags:

c#

I have a problem in my code where the average is a whole number even though I specify it as a double data type. What could be the problem?

using System;
using static System.Console;
using System.Linq;
class TemperaturesComparison
{
   static void Main()
   {
     int[] temp = new int[5];
     int i = 0;
     while (i < 5)
     {
       int eachTemp = int.Parse(ReadLine());
       if (eachTemp < -30 || eachTemp > 130) continue; //skips 
       temp[i] = eachTemp;
       i++;
     }
     
     if (temp[0] < temp[1] && temp[1] < temp[2] && temp[2] < temp[3] && temp[3] < temp[4]) WriteLine("Getting warmer");
     else if (temp[0] > temp[1] && temp[1] > temp[2] && temp[2] > temp[3] && temp[3] > temp[4]) WriteLine("Getting cooler");
     else WriteLine("It's a mixed bag");
     
     foreach(int number in temp)
     {
     Console.Write(number + " ");
     }
     double average = temp.Sum()/5;
     WriteLine("");
     WriteLine(average);
     
   }
}

For instance, I input: 88 99 78 86 77

The average is 85 instead of 85.6

like image 870
Javanese Python Avatar asked Oct 15 '25 15:10

Javanese Python


1 Answers

The number is converted to double after the integer division (see the docs) is performed (so the division result will not have decimal part), you need to convert one of the arguments to double before the division:

double average = (double)temp.Sum()/5;

or just change the divisor to be 5.0 (which will become of type double)

double average = temp.Sum()/5.0;

Also note that you can just use LINQ's Average which has return type of double for overload accepting enumerable of int:

var average = temp.Average();
like image 128
Guru Stron Avatar answered Oct 17 '25 04:10

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!