You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重载方法TipCalculation程序无计算输出问题排查与解决

小费计算程序的方法重载问题解决

题目要求

  • 创建名为TipCalculation的C#程序,包含两个重载的GetBill方法:
    1. 参数为double类型餐价 + double类型小费比例(例:30.00和0.20,0.20代表20%小费);
    2. 参数为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:35:28