作业 - 排序:/双弦问题

时间:2015-11-19 14:23:17

标签: c# string

我完成了这项作业,无法弄明白。 我需要询问用户他想要输入多少城镇名称。例如5。 然后,他输入了5个镇名。 之后,我们需要找到名称的平均长度,并向他显示字母数少于平均长度的名称。谢谢你的共享时间:) 到目前为止我的代码:

static void Main(string[] args)
{

    int n;
    Console.WriteLine("How many town names would you like to enter:");
    n = int.Parse(Console.ReadLine());
    string[] TownNames = new string[n];
    Console.Clear();
    Console.WriteLine("Enter {0} town names:", n);
    for (int i = 0; i < n; i++)
    {
        Console.Write("Enter number {0}: ", i + 1);
        TownNames[i] = Convert.ToString(Console.ReadLine());
    }

    Console.ReadKey(true);
}

static void Average(double[] TownNames, int n)
{

}

2 个答案:

答案 0 :(得分:1)

你走在正确的轨道上。您在main方法中拥有的是一个数组,您可以使用用户输入的城镇名称填充该数组。我将这两个标准分成不同的方法:

int FindAverage(string[] towns);
IEnumerable<string> FilterShortNamedTowns(string[] towns, int average);

平均值应该非常简单。您只需要根据Length property exposed by the string class计算平均值。此属性记录字符串中的字符数。

private static int FindAverage(string[] towns)
{
   int totalLength = 0;
   foreach(var town in towns)
      totalLength += town.Length;

   return totalLength / towns.Length;

   // This can be shortened to the following use LINQ but the above shows the algorithm better.
   // return towns.Select(town => town.Length).Average();
}

第二种方法应该只是循环再次收集,只返回长度<1的城镇。平均。

private static IEnumerable<string> FilterShortNamedTowns(string[] towns, int average)
{
   return towns.Where(town => town.Length < average);
}

答案 1 :(得分:1)

要查找名称的平均长度,您必须总结所有名称的长度。然后用名字数除以。

Contact