我有一个涉及模拟赛马并报告谁是第一,第二和第三的项目。我已经一路走来为每个距离测量制作一个随机数,无论哪匹马的总数最高。我无法将第一,第二和第三位置于右下方。我有一个数组的总数,我不太确定现在去哪里。
Console.Write ("Type 'Begin' to start the race. ");
string startRace = Console.ReadLine ();
if (startRace == "Begin")
{
Console.Clear ();
Console.WriteLine ("You may now begin the race.");
Console.Clear ();
int[] tot = new int[numberOfHorses];
for (int i = 0; i < numberOfHorses; i++)
{
Console.Write (string.Format("{0, 10}: ", horseName[i]));
int total = 0;
for (int n = 1; n <= furlongs; n++)
{
int randomNum = rnd.Next (0, 10);
Console.Write (" " + randomNum + " ");
total = total + randomNum;
}
tot[i] = total;
Console.Write (" | " + total);
Console.WriteLine (" ");
} //This is where I start to get unsure of myself.
int firstPlace = Int32.MinValue
for (int place = 0; place < numberOfHorses; place++)
{
if (tot[place] > firstPlace)
{
firstPlace = tot[place];
}
}
}
'numberOfHorses'是用户决定参加比赛的马数,'horseName'是用户为每匹马命名的。谢谢。 :)
答案 0 :(得分:1)
您需要一个排序功能。而不是:
int firstPlace = Int32.MinValue
for (int place = 0; place < numberOfHorses; place++)
{
if (tot[place] > firstPlace)
{
firstPlace = tot[place];
}
}
试试这个:
int[] horseIndexes = new int[numberOfHorses];
for (int place = 0; place < numberOfHorses; place++)
{
horseIndexes[place] = place ;
}
// this is the sorting function here
// (a,b) => tot[b] - tot[a]
// it will sort in descending order
Array.Sort(horseIndexes, (a,b) => tot[b] - tot[a]);
for (int place = 0; place < horseIndexes.Length && place < 3; place++)
{
Console.WriteLine("place: " + (place+1));
Console.WriteLine("horse: " + horseName[horseIndexes[place]);
Console.WriteLine("total: " + tot[horseIndexes[place]);
}
使用LINQ表达式有更好的方法,但希望这个例子是最容易理解的。
答案 1 :(得分:0)
Emerald King应该已经知道如何在列表中找到最高的数字。取出最顶部的数字(将其设置为0)然后重复该过程以找到第二个,并再次找到第三个。