我输入了这个代码作为家庭作业,它的工作原理。但是,方法部分不正确。该方法应从表单中获取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
}
答案 0 :(得分:1)
考虑到在检查字段是否为空或无法转换为小数时显示相同的错误,请将两者合并:
if (string.IsNullOrEmpty(txtCost.Text) || !decimal.TryParse(txtCost.Text, out cost))
{
MessageBox.Show("Please enter a number for the cost", "Error");
return;
}
(与txtPercent相同。)
您的主要问题是您不使用参数。您的方法可以像这样重写:
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
等变量名称很糟糕。使用正确的描述性名称不会受到惩罚;如果他或她不必首先弄清楚变量包含什么,下一个出现的人将更容易维护你的代码。