C#基础:多数组场景下用户输入获取与操作的房费计算问题
核心逻辑说明
你定义的name和price是下标对应的关联数组,相同下标位置的元素对应同一个房型的名称和单价,只要拿到正确的数组下标,就能同时获取对应房型的两个属性。用户输入通过Console.ReadLine()获取,转换为对应类型后即可参与计算。
现有代码错误及修正
- 循环输出房型时硬编码了序号1,导致所有房型选项的序号都显示为1,需要用
i+1动态生成序号 - 数组下标从0开始,用户输入的房型编号是1~4,需要减1后才能匹配数组的对应下标
- 总房费计算逻辑错误,原代码是晚数乘房型编号,正确应为晚数乘对应房型的单价
- 最终输出语句中的房型占位符、硬编码的5晚,都需要替换为实际获取的变量值
修正后代码(原版英文输出)
static void Main(string[] args) { string[] name = { "Single", "Double", "Luxury", "Penthouse" }; double[] price = { 45.50, 99.99, 165.25, 1095.50 }; Console.WriteLine("Room Types\n"); for (int i = 0; i < name.Length; i++) { Console.WriteLine($"{i+1}. {name[i]} ${price[i]} per night"); } Console.Write("\nPlease select a room type 1, 2, 3 or 4: "); int roomIndex = Int32.Parse(Console.ReadLine()) - 1; Console.Write("Please enter the number of nights: "); int nights = Int32.Parse(Console.ReadLine()); double totalCost = price[roomIndex] * nights; Console.WriteLine($"\nThank you, the total cost for staying in the {name[roomIndex]} room for {nights} nights is ${totalCost}"); Console.ReadLine(); }
中文本地化版本代码
static void Main(string[] args) { string[] name = { "单人房", "双人房", "豪华房", "顶层套房" }; double[] price = { 45.50, 99.99, 165.25, 1095.50 }; Console.WriteLine("房型列表\n"); for (int i = 0; i < name.Length; i++) { Console.WriteLine($"{i+1}. {name[i]} 每晚价格 {price[i]} 美元"); } Console.Write("\n请选择房型(输入1/2/3/4):"); int roomIndex = Int32.Parse(Console.ReadLine()) - 1; Console.Write("请输入入住晚数:"); int nights = Int32.Parse(Console.ReadLine()); double totalCost = price[roomIndex] * nights; Console.WriteLine($"\n感谢您的选择,您入住{name[roomIndex]} {nights}晚的总费用为 {totalCost} 美元"); Console.ReadLine(); }
内容的提问来源于stack exchange,提问作者Dak Zevon
相关产品推荐
相关产品推荐

