我正在尝试在没有条件语句和循环的情况下重写我的代码。 我的代码是根据这样的指令编写的,但另外没有循环和条件语句
将输入作为开始月份和日期到结束月份和日期的程序
计算总价。
假定的输入始终正确。
输入范围为同年1月1日至12月31日
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;
}
关于java - 如何编写没有 for 和 if 语句的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61552242/