我试图在没有条件语句和循环的情况下重写我的代码。我的代码是基于这样的指令编写的,但是没有循环和条件语句
一个将输入作为开始月份和日期至结束月份和日期以及
计算总价。
假定输入始终正确。
输入范围为同年1月1日至12月31日
1月1/1是星期一。
输入开始日期始终为星期一
偶数月包含31天,奇数月包含30天
价格平日-> $ 2
星期六-> $ 3
周日-> $ 5
如果客户预订超过50天,价格将稳定在1美元
public class test {
int startMonth;
int startDay;
int endMonth;
int endDay;
int totalDate;
public test (int startMonth, int startDay, int endMonth, int endDay) {
this.endMonth = endMonth;
this.endDay = endDay;
this.startMonth = startMonth;
this.startDay = startDay;
}
public int getPrice() {
getTotalDate();
int price = 0;
int discount = totalDate > 50 ? totalDate - 50 : 0;
System.out.println("discount " + discount);
totalDate = totalDate > 50 ? 50 : totalDate % 50;
System.out.println("totalData : " + totalDate);
int sunDay = totalDate/7;
int satDay = totalDate/7 + (totalDate%7)/6;
int weekDay = totalDate - sunDay - satDay;
price+= sunDay*5 + satDay*3 + weekDay*2;
return price + discount;
}
public int getTotalDate() {
int gapOfMonth = endMonth - startMonth;
totalDate = gapOfMonth*30 + (gapOfMonth +1)/2 + (endDay - startDay);
return totalDate;
}
public static void main (String[] args) {
test t = new test(1,1,2,30);
System.out.println("test");
System.out.println(t.getPrice());
}
}
无需三元就可以完成它
public int getPrice(int totalDay) {
int totalPrice = 0;
int difference = totalDay-50;
//from https://stackoverflow.com/a/2707438/529282
int absDifference = difference*(1-2*((3*difference)/(3*difference+1)));
//this essentially gives the minimum value between totalDay and 50
int before50 = (totalDay+50-absDifference)/2;
int after50 = totalDay-before50;
totalPrice += after50;
//the before 50 is where the complex calculation is needed
int before50 = totalDay - after50;
//first, the base price for weekday
totalPrice += before50 * 2;
//then we add the whole week difference (sat+sun price - weekday price)
totalPrice += (before50 / 7) * 4;
//the we add the stray saturday if any
totalPrice += (before50 % 7) / 6;
return totalPrice;
}
public int getTotalDate() {
int totalDate = 0;
//add month difference
totalDate += 30 * (endMonth - startMonth);
//add day difference
totalDate += (endDay - startDay);
//add the extra from having 31 days every two months
totalDate += (endMonth - startMonth) / 2;
//if the month start from even months and the end month is different,
//add another day since it ends with 31
//the trick here, if startMonth == endMonth, startMonth/endMonth = 1,
//so 1-1 is 0, nothing get added
//while if startMonth<endMonth, startMonth/endMont = 0, so 1-0 is 1
totalDate += ((startMonth + 1) % 2) * (1 - startMonth / endMonth);
return totalDate;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句