接收批发成本和加价 % 作为参数并返回零售价 C# 的方法
本文关键字:参数 返回 零售价 方法 | 更新日期: 2023-09-27 18:30:39
我为家庭作业输入了此代码,它有效。但是,方法部分不正确。该方法应从窗体中接收 2 个值(批发价和加价百分比)作为参数,并返回零售价。这是我到目前为止所拥有的,我只是想知道我需要移动到哪里才能正确使用方法。
{
InitializeComponent();
}
private void CalculateRetail()//method header
{//method body
decimal Cost, //variables
Percent,
Perc,
PercAmt,
FinCost;
Cost = Convert.ToDecimal(txtCost.Text);
Percent = Convert.ToDecimal(txtPercent.Text);
Perc = (Percent / 100);
PercAmt = Cost * Perc;
FinCost = Cost + PercAmt;
lblFinCost.Text = "The Retail Price with markup is " + FinCost.ToString("C2"); //output to label
}//end method body
private void btnCalc_Click(object sender, EventArgs e)
{
decimal Cost;
decimal Percent;
lblFinCost.Text = "";
if (string.IsNullOrEmpty(txtCost.Text)) // input validation check to make sure not blank
{
MessageBox.Show("Please enter a number for the cost", "Error");
return;
} //end if
if (!decimal.TryParse(txtCost.Text, out Cost)) // input validation check to make sure is whole number
{
MessageBox.Show("Please enter a number for the cost", "Error");
return;
}
if (string.IsNullOrEmpty(txtPercent.Text)) // input validation check to make sure not blank
{
MessageBox.Show("Please enter a number for the cost", "Error");
return;
} //end if
if (!decimal.TryParse(txtPercent.Text, out Percent)) // input validation check to make sure is whole number
{
MessageBox.Show("Please enter a number for the cost", "Error");
return;
}
CalculateRetail(); //call method once error check passes
}
private void btnClear_Click(object sender, EventArgs e)
{
txtCost.Text = "";//clear form
txtPercent.Text = "";
lblFinCost.Text = "";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close(); //close form
}
考虑到您在检查字段是否为空或无法转换为小数时显示相同的错误,请将两者结合起来:
if (string.IsNullOrEmpty(txtCost.Text) || !decimal.TryParse(txtCost.Text, out cost))
{
MessageBox.Show("Please enter a number for the cost", "Error");
return;
}
(与 txt% 相同。
您的主要问题是不使用参数。您的方法可以像这样重写:
private void CalculateRetail(decimal cost, decimal percent)
{
var percAmt = Cost * (percent / 100);
var finCost = cost + percAmt;
lblFinCost.Text = "The Retail Price with markup is " + finCost.ToString("C2");
}
然后这样称呼:
CalculateRetail(cost, percent);
请注意,局部变量应该是 CamelCase,而不是 PascalCase,即它们不应该以大写字母开头。
还要避免只描述我们已经可以看到的内容的注释;这些只会使你的代码混乱:
//end method body
//output to label
//variables
顺便说一下,像 finCost
和 percAmt
这样的变量名称是不好的。使用适当的描述性名称不会受到惩罚;下一个人将更容易维护你的代码,如果他或她不必首先弄清楚变量包含什么。