對於作業問題感到遺憾,我知道有些人不喜歡他們,但我很茫然。 我已經寫了一個代碼,根據我的任務,有用戶輸入他們想投票等,這一切都有效。第二部分的任務是修改它,所以如果兩個候選人有相同的投票,而不是在第三個是「...」第二個是「...」(第三個是第三個) ...「第二個輸出是」... + ...「第一個是」...「以相同的票數輸出兩位候選人
這是我的代碼,
class Program
{
static void Main(string[] args)
{
//create empty arrays
int[] votes = new int[5];
string[] names = { "Ahmed", "Boo", "Celine", "Didi", "Elaine" };
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine("{0} {1}", i, names[i]);
}
//input votes
Input(votes);
//sort votes
Sort(votes, names);
if (votes[0] > 0)//If there are any votes for the top candidate then do not display the output
{
//output sorted data
Console.WriteLine("\nVote summary");
Output(votes, names);
Console.WriteLine("\nIn third place: {0}", names[2]);
Console.WriteLine("In second place: {0}", names[1]);
Console.WriteLine("And the winner is: {0}", names[0]);
}
else
{
Console.WriteLine("No votes were made!");
}
Console.ReadLine();
}//end Main
static void Input(int[] arr)
{
int vote = EnterInt("Enter number of candidate you wish to vote for (0 to 4) or -1 to quit:");
while (vote != -1)
{
if (vote < 0 || vote > 4)
{
Console.WriteLine("Invalid vote");
}
else
{
arr[vote]++;
}
vote = EnterInt("Enter number of candidate you wish to vote for (0 to 4) or -1 to quit:");
}//end while
}//end InputArray
public static void Sort(int[] votes, string[] names)
{
for (int pass = 1; pass < votes.Length; pass++)
{
int smallestPos = FindSmallest(votes, votes.Length - pass);
if (smallestPos != votes.Length - pass)
{
Swap(votes, smallestPos, votes.Length - pass);
Swap(names, smallestPos, votes.Length - pass);
}
}//end for
}//end Sort
public static int FindSmallest(int[] votes, int num)
{
int smallestPos = 0;
for (int i = 1; i <= num; i++)
{
if (votes[i] < votes[smallestPos])
{
smallestPos = i;
}
}//end for
return smallestPos;
}//end FindSmallest
public static void Swap(int[] votes, int first, int second)
{
int temp = votes[first];
votes[first] = votes[second];
votes[second] = temp;
}//end Swap
public static void Swap(string[] names, int first, int second)
{
string temp = names[first];
names[first] = names[second];
names[second] = temp;
}//end Swap
public static void Output(int[] votes, string[] names)
{
for (int i = 0; i < votes.Length; i++)
{
Console.WriteLine("{0} {1}", names[i], votes[i]);
}//end for
}//end Output
static int EnterInt(string prompt)
{
Console.Write(prompt);
int num;
while (!int.TryParse(Console.ReadLine(), out num))
{
Console.Write("Error! Please enter an integer number:");
}//end while
return num;
}
}
謝謝你的幫助。
如果你只在乎前三名則只是做比較,有4種可能性,前兩名分別是相等的,第二和第三都是平等的,所有3個都是平等的,或者一個都不相等。如果你想在包含一個或多個關係的情況下包含第四個和第五個候選者,它會變得更復雜一些。 – juharr
如果您創建一個對象來容納所有內容(例如'類Candidate',其屬性爲'Name'和'Votes'),則不需要2次交換。至於任務有幾種方法,例如使用排序。或者您可以簡單地找到最大投票數的候選人,記住該數字,輸出所有具有相同數字的候選人(用+連接),找到下一個較低的最高票數,重複。 – Sinatr
我可能會誤解這一點,但當然你可以添加一個if來比較[1]和[2],如果它們相等,那麼輸出你的第二個... + ...,如果他們不是那麼使用你現有的邏輯? –