酒店预订价格代码周末价格(逻辑执行问题)



当用户预订周五和周六的一天作为周末额外费用时,我试图多收取30美元,但我无法获得当天的预订,也无法添加额外费用。到目前为止,我已经这样做了:

private void btnCalculate_Click(object sender, EventArgs e)
{
DateTime dtArrivalDate;
DateTime.TryParse(txtArrivalDate.Text, out dtArrivalDate);
DateTime dtDepartureDate;
DateTime.TryParse(txtDepartureDate.Text, out dtDepartureDate);
TimeSpan tsDuration = dtDepartureDate.Subtract(dtArrivalDate);
int costPerNight = 120;
for (DateTime date = dtArrivalDate; date <= dtDepartureDate; date = date.AddDays(1))
{
DayOfWeek dw = date.DayOfWeek;
string days = dw.ToString();
int weekendCost = 0;
if (dw == DayOfWeek.Friday || dw == DayOfWeek.Saturday)
{
weekendCost = weekendCost + 30;
dw++;
int totalCost = tsDuration.Days * costPerNight + weekendCost;
int avgPricePerNight = (tsDuration.Days * costPerNight + weekendCost) / tsDuration.Days;
txtNights.Text = tsDuration.Days.ToString("n");
txtTotalPrice.Text = totalCost.ToString("n");
txtAvgPrice.Text = avgPricePerNight.ToString("n");
}
else
{
int totalCost = tsDuration.Days * costPerNight;
int avgPricePerNight = (tsDuration.Days * costPerNight) / tsDuration.Days;
txtNights.Text = tsDuration.Days.ToString("n");
txtTotalPrice.Text = totalCost.ToString("n");
txtAvgPrice.Text = avgPricePerNight.ToString("n");
}
}    
}
for (DateTime date = dtArrivalDate; date <= dtDepartureDate; date = date.AddDays(1))

与您的问题没有直接关系,但应该是date < dtDepartureData

无论如何,问题是你每天都要检查,但在循环中你要重新计算并显示价格。更好的代码应该是这样的(保持每天迭代的基本想法(:

int costPerNight = 120;
int weekendCost = 0;
for (DateTime date = dtArrivalDate; date < dtDepartureDate; date = date.AddDays(1))
{
DayOfWeek dw = date.DayOfWeek;
if (dw == DayOfWeek.Friday || dw == DayOfWeek.Saturday)
{
weekendCost = weekendCost + 30;
}
}
int totalCost = tsDuration.Days * costPerNight + weekendCost;
int avgPricePerNight = (tsDuration.Days * costPerNight + weekendCost) / tsDuration.Days;
txtNights.Text = tsDuration.Days.ToString("n");
txtTotalPrice.Text = totalCost.ToString("n");
txtAvgPrice.Text = avgPricePerNight.ToString("n");

我们计算每个周末的一天,然后在循环结束后,计算出总价。

顺便说一句,为了更好的可读性,这些30120值应该用命名的常量代替。

相关内容

  • 没有找到相关文章

最新更新