重载方法TipCalculation程序无计算输出问题排查与解决
小费计算程序的方法重载问题解决
题目要求
- 创建名为
TipCalculation的C#程序,包含两个重载的GetBill方法:- 参数为
double类型餐价 +double类型小费比例(例:30.00和0.20,0.20代表20%小费); - 参数为
double类型餐价 +int类型小费金额(例:30.00和5,5代表5美元固定小费)。
- 参数为
- 每个
GetBill方法需要输出:餐价、小费占餐价的比例、小费金额、总金额(餐价+小费),同时程序需包含Main()方法演示两个重载的使用。
问题与修复
编写代码后,输入合法数值程序却不执行任何计算。最初尝试通过GetType()判断输入的小费类型来匹配重载方法,逻辑错误导致失败;改用TryParse系列方法解析输入后,问题解决。
原错误Main代码
static void Main(string[] args) { Console.WriteLine("Please enter the meal price: "); double mealPrice = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please enter the tip percentage: "); var tipPercentage = Console.ReadLine(); Type tipType = tipPercentage.GetType(); if(tipType.Equals(typeof(double))) { double doubleTypeTip = Convert.ToDouble(tipPercentage); double tipValD = doubleTypeTip / 10; GetBill(mealPrice, tipValD); } if (tipType.Equals(typeof(int))) { int intTypeTip = Convert.ToInt32(tipPercentage); GetBill(mealPrice, intTypeTip); } }
错误根源
Console.ReadLine()的返回值永远是string类型,所以tipPercentage.GetType()得到的始终是typeof(string),两个if条件永远不会触发,自然无法调用任何GetBill重载方法。
修改后的正确Main代码
static void Main(string[] args) { Console.WriteLine("Please enter the meal price: "); double mealPrice = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Please enter the tip percentage: "); var tipPercentage = Console.ReadLine(); double doubleTypeTip; int intTypeTip; if (Double.TryParse(tipPercentage, out doubleTypeTip)) { GetBill(mealPrice, doubleTypeTip); } else if(Int32.TryParse(tipPercentage, out intTypeTip)) { GetBill(mealPrice, intTypeTip); } }
修复逻辑说明
- 先用
Double.TryParse尝试将输入字符串解析为double类型,成功则调用对应比例参数的GetBill方法; - 若
double解析失败,再用Int32.TryParse尝试解析为int类型,成功则调用固定金额参数的GetBill方法; - 这种方式能准确判断输入的数值类型,正确匹配对应的方法重载。
内容的提问来源于stack exchange,提问作者diogenes31
相关产品推荐
相关产品推荐

