Using one variable to enter 5 integers C #

I am using C # and I am trying to find the average of 5 values, but I can only use 2 variables.

How can you enter 5 integers in one variable and display the average number of integers

+4
source share
6 answers

Take the input values ​​in an integer list or array, then use the following code

List<int> intlist=new List<int>();
intlist.Add(2);
intlist.Add(3);
..
..
var average= intlist.Average();

Using Average will calculate the average of the sequence of all integers in the list.

UPDATE : or if the point is to use integers, then you need to use the following code (don't forget to check the entries readline())

public decimal Average()
{
 int value = 0;
 for(int i=0;i<5;i++)
 {
  value+=ConvertToInt32(Console.ReadLine());
 }
 return value/5;
}
+4

:

var list = new List<int>(){ 1, 2, 3, 4, 5 };
var average = list.Average();

Average,

Enumerable, , . Sum

+6

List<int> Enumerable.Average:

List<int> numbers = new List<int>{ 10, 20, 30, 40, 50 };
double average = numbers.Average();  // 30.0

List.Add :

numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
// ...
+6

? , -

 int[] input = new int[5];
        input[0] = 5;
        input[1] = 40;
        input[2] = 15;
        input[3] = 50;
        input[4] = 25;

        int sum = 0;
        foreach(int i in input)
        {
            sum = sum + i;
        }
        sum = sum / input.Length;
        Console.WriteLine(sum.ToString());

@up , !

+3

, - . -:

private int sum = 0;
private int count = 0;

while (user inputs valid number)
{ 
    sum += userInput;
    count++;
}

return sum / count;

.

+3

List<int>,

 int[] arr=new int[5];
 arr[0]=10;arr[1]=20;...arr[4]=50;
 int sum=0;
 foreach(int x in arr)
  {
     s+=x;

   }
 s=s/arr.Length;//s is average

 List<int> list = new List<int>(){ 1, 2, 3, 4, 5 };
 var average = list.Average();
+2

All Articles