这里是问题:
创建一个名为 TipCalculation 的程序,其中包含两个重载方法——一个接受双倍的餐费和小费(例如,30.00 和 0.20,其中 0.20 表示 20% 的小费),另一个接受双倍的餐费以及整数形式的小费金额(例如,30.00 和 5,其中 5 表示 5 美元的小费)。每种方法都显示用餐价格、小费占用餐价格的百分比、以美元计的小费以及用餐加小费的总和。包括一个演示每个方法的 Main() 方法。
这是我写的代码。问题是当我输入正确的格式输入时它根本不做任何计算。我怀疑这可能是我造成的歧义。但我认为 if 条件应该为正确的参数适当地选择正确的方法。
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class TipCalculation
{
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);
}
}
public static void GetBill(double mealPrice, double tipPercentage)
{
double tip = mealPrice * tipPercentage;
double bill = mealPrice + tip;
Console.WriteLine("The meal price is {0:C3}\n"+
"The tip is {1:C3}\n" +
"The total bill is {3:C3}\n",mealPrice, tip, bill);
}
public static void GetBill(double mealPrice, int tipPercentage)
{
double tip = mealPrice * (tipPercentage/10);
double bill = mealPrice + tip;
Console.WriteLine("The meal price is {0:C3}\n" +
"The tip is {1:C3}\n" +
"The total bill is {3:C3}\n", mealPrice, tip, bill);
}
}
}
var
是 not 动态类型
使用
var
是一个 static inferred 类型,这意味着虽然您作为编码人员不必担心它,但在幕后它会有一个适当的静态编译类型
在所有 dotnet 语言中进行动态类型化的唯一方法是使用
dynamic
,或者经典的矫枉过正 object
type
我想说的是:
var tipPercentage = Console.ReadLine();
Type tipType = tipPercentage.GetType();
真的会总是意思是:
string tipPercentage = Console.ReadLine();
Type tipType = tipPercentage.GetType(); //tipType == typeof(string)
因此,您的 main() 方法末尾的两个分支都不会触发,因此什么也不会发生
你也可以通过更多地依赖 double 来让事情变得更容易一些。原因是因为 int
10
只是 10.00
作为双精度数。相反,说10.50
将是一个问题。 C# 也有用于货币计算的 decimal 类型 但这里有点多
这是您的 Main() 方法,有一些修复,它简化了逻辑,但也包括一些验证逻辑
//Note: it is ideal to use double.TryParse() to better handle exception throws from faulty inputs
Console.WriteLine("Please enter the meal price: ");
string mealPrice = Console.ReadLine();
Console.WriteLine("Please enter the tip percentage: ");
string tipPercentage = Console.ReadLine();
if (double.TryParse(mealPrice, out double meal) && double.TryParse(tipPercentage, out double tip))
{
GetBill(meal, tip;)
}
else
{
//print message, or throw an exception like in the line below
Console.WriteLine("Could not parse inputs");
//throw new Exception("Could not parse inputs");
}
在你的代码中:
var tipPercentage = Console.ReadLine();
Console.ReadLine()
返回一个 String
,所以 tipPercentage
将是 String
类型,并且您的 if
语句测试 tipPercentage
的运行时类型都不会评估为 true,因此没有计算执行。