4

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

2 Answers2

5

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();
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
1

If you declare the array of double type instead of int it will work as expected. Just do this :

double[] temp = new double[5];

Output

enter image description here

Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43