C#计算int数组中值的平均值

时间:2016-06-22 11:39:15

标签: c# arrays mean

当我尝试打印int数组中的平均值并且打印出与我有值的次数完全不同的东西时,会出现什么问题。

int[] numbers;
numbers = new int[5];
Console.WriteLine("give five integer numbers:");
numbers[0] = Int32.Parse(Console.ReadLine());
numbers[1] = Int32.Parse(Console.ReadLine());
numbers[2] = Int32.Parse(Console.ReadLine());
numbers[3] = Int32.Parse(Console.ReadLine());
numbers[4] = Int32.Parse(Console.ReadLine());
int sum = 0;

foreach (int x in numbers) {
    sum += x;
    int aver = sum / numbers.Length;  
    Console.WriteLine("average: {0}",aver);
}

4 个答案:

答案 0 :(得分:5)

平均值应该在循环之外:

foreach (int x in numbers) 
{
   sum += x;
}

int aver = sum / numbers.Length;  
Console.WriteLine("average: {0}",aver);

或使用Linq扩展方法:

Console.WriteLine("average: {0}", numbers.Average());

答案 1 :(得分:3)

你可以将循环改写为

int sum = 0;
foreach (int x in numbers)
{
    sum += x;
}
int aver = sum / numbers.Length;

或只是将计算作为

int aver = numbers.Average();

使用Linq。

答案 2 :(得分:2)

或者使用linq:var aver = numbers.Average();

https://msdn.microsoft.com/en-us/library/bb399409(v=vs.110).aspx

我将在Average() so;)

下完成我的答案
  public static double Average(this IEnumerable<int> source) {
       if (source == null) throw Error.ArgumentNull("source");
       long sum = 0;
       long count = 0;
       checked {
          foreach (int v in source) {
              sum += v;
              count++;
          }
       }
       if (count > 0) return (double)sum / count;
       throw Error.NoElements();
   }

答案 3 :(得分:0)

更改

foreach (int x in numbers) {
    sum += x;
}
int aver = sum / numbers.Length;  Console.WriteLine("average: {0}",aver);

class IDigitalPoint
{
public:
    virtual void CommonDigitalMethod1() = 0;
};


enum class Direction : bool { Input, Output };

template <Direction direction>
class DigitalPoint : public IDigitalPoint
{
public:
    void CommonDigitalMethod1() {}
    void ExtraCommonDigitalMethod2() {}

    virtual void DigitialMethod1() = 0;
};

class DigitalInputPoint : public DigitalPoint<Direction::Input>
{
public:
    void DigitialInputMethod1() {}
    void ExtraDigitialInputMethod2() {}

    // This is like DigitialInputMethod1()
    virtual void DigitialMethod1() override
    {}
};

class DigitalOutputPoint : public DigitalPoint<Direction::Output>
{
public:
    void DigitialOutputMethod1() {}
    void ExtraDigitialOutputMethod2() {}

    // This is like DigitialOutputMethod1()
    virtual void DigitialMethod1() override
    {}
};