【发布时间】:2012-01-14 20:22:01
【问题描述】:
我这里有一段代码,记录了 4 个房间收集的瓶子数量。当用户输入退出时,程序会吐出每个房间收集的瓶子数量,并确定收集瓶子数量最多的房间。我使用了数组方法,但我不应该使用这种方法,只是为了展示数组的有用性。任何人都可以给我任何指示吗?
namespace BottleDrive
{
class Program
{
static void Main(string[] args)
{//Initialize array of rooms to 4
int[] rooms = new int[4];
//Start of while loop to ask what room your adding into.
while (true)
{
Console.Write("Enter the room you're in: ");
//If user enters quit at anytime, the code will jump out of while statement and enter for loop below
string quit = Console.ReadLine();
if (quit == "quit")
//Break statement allows quit to jump out of loop
break;
//Variable room holds the number of bottles collect by each room.
int room = int.Parse(quit);
Console.Write("Bottles collected in room {0}: ", room);
// This line adds the count of bottles and records it so you can continuously count the bottles collected.
rooms[room - 1] += int.Parse(Console.ReadLine());
}
//This for statement lists the 4 rooms and their bottle count when the user has entered quit. An alternative to below
/*for (int i = 0; i < rooms.Length; ++i)
Console.WriteLine("Bottles collected in room {0} = {1}", i + 1, rooms[i]);*/
int maxValue = 0;//initiates the winner, contructor starts at 0
int maxRoomNumber = 0;//initiates the room number that wins
for (int i = 0; i < rooms.Length; ++i)//This loop goes through the array of rooms (4)
{
if (rooms[i] > maxValue)//Makes sure that the maxValue is picked in the array
{//Looking for room number for the
maxValue = rooms[i];
maxRoomNumber = i + 1;
}//Writes the bottles collected by the different rooms
Console.WriteLine("Bottles collected in room {0} = {1}", i + 1, rooms[i]);
}
//Outputs winner
Console.WriteLine("And the Winner is room " + maxRoomNumber + "!!!");
}
}
}
【问题讨论】:
-
您可以使用
List<int>和 LINQ 来展示无用的数组是如何... -
LINQ 是我的班级尚未涉及的内容。还有比 LINQ 更原始的方式吗?
-
插入强制性指针笑话...“这里有一些... 0x013d2da0 和 0x4e326dbb”
-
@Marc - 是时候升级到 64 位了,你不觉得吗? ;-)