2015-11-19 50 views
-1

我得到這個家庭作業,無法弄清楚。 我需要詢問用戶他想輸入多少個城鎮名稱。例如5. 然後,他輸入5個城鎮名稱。 之後,我們需要找到名稱的平均長度,並向他顯示字母少於平均長度的名稱。感謝您的分享時間:) 到目前爲止我的代碼:作業 - 分類:/雙 - 字符串prolem

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

您是用哪種語言開發此代碼的?請添加合適的標籤。您可以通過點擊帖子下方的「修改」鏈接來完成此操作。 – reporter

+0

記者是對的,你需要用人們可以幫助的語言標記問題 –

+0

你卡在哪裏?您的代碼以何種方式無法按預期工作?你爲什麼期望你的城鎮的名字是'雙'? – David

回答

1

你在正確的軌道上。你在主要方法中有一個數組,你用用戶輸入的城鎮的名字填充。我會將這兩個標準分爲不同的方法:

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(); 
} 

第二種方法應該只通過收集循環一次只返回城鎮,其中長度<平均水平。

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

要找到名稱的平均長度,您必須總結所有名稱的長度。然後將其除以名稱的數量。

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);