我目前正在开发一个利用DateTime变量查找各种日期之间旅行费用的项目。大多数点击事件都会触发,但总价和平均价格的计算不会运行。任何帮助将不胜感激。
以下是代码:
private void btnCalculate_Click(object sender, EventArgs e)
{
DateTime arrival = DateTime.Parse(txtArrivalDate.Text);
DateTime departure = DateTime.Parse(txtDepartureDate.Text);
TimeSpan numDays = departure - arrival;
int ndays = numDays.Days;
txtNights.Text = ndays.ToString();
decimal totalPrice = 0;
txtTotalPrice.Text = totalPrice.ToString("c");
decimal avprice = totalPrice / ndays;
txtAvgPrice.Text = avprice.ToString("c");
DateTime nightToCharge = arrival;
decimal pricePerNight = 0m;
int i = ndays;
while (i > 0)
{
DayOfWeek dayOfweek = nightToCharge.DayOfWeek;
if (dayOfweek == DayOfWeek.Friday ||
dayOfweek == DayOfWeek.Saturday)
{
pricePerNight = 150m;
}
else
{
pricePerNight = 120m;
}
i--;
nightToCharge = nightToCharge.AddDays(1);
totalPrice += pricePerNight;
}
}
答案 0 :(得分:0)
您的价格未被显示,因为您在计算价格之前设置了TextBox
文本的值。您还需要在计算总金额之前设置平均价格。
只需计算平均值并在while
循环后分配价格值:
while (i > 0)
{
// Code omitted for brevity
}
decimal avprice = totalPrice / ndays;
txtTotalPrice.Text = totalPrice.ToString("c");
txtAvgPrice.Text = avprice.ToString("c");