家庭作业-有点像:/双字符串prolem
本文关键字:字符串 prolem 家庭作业 | 更新日期: 2023-09-27 18:22:33
我收到了这项家庭作业,搞不明白。我需要询问用户他想输入多少城镇名称。例如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)
{
}
你走在了正确的轨道上。主方法中有一个数组,用用户输入的城镇名称填充该数组。我将把这两个标准分成不同的方法:
int FindAverage(string[] towns);
IEnumerable<string> FilterShortNamedTowns(string[] towns, int average);
平均应该很容易。您只需要根据字符串类公开的Length属性计算平均值。此属性跟踪字符串中的字符数。
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();
}
第二种方法应该只是再次循环通过集合,并且只返回Length<平均的
private static IEnumerable<string> FilterShortNamedTowns(string[] towns, int average)
{
return towns.Where(town => town.Length < average);
}
要找到名称的平均长度,必须将所有名称的长度相加。然后除以名字的数目。
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();
int totalLength = 0; // holds total length of names
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());
totalLength += TownNames[i].Length; // add the name length to total
}
int average = totalLength/n; // calculate average
Console.Clear();
Console.WriteLine("town names lower than average length:");
for (int i = 0; i < n; i++)
{
if (TownNames[i].Length < average) // print values when the length name is less than average.
{
Console.WriteLine("Town {0} : {1}", i + 1, TownNames[i]);
}
}
Console.ReadKey(true);