本题代码如下
public class Tax {
public double distance;
public boolean atNight;//白天 false 黑夜 ture
public int time;
//无参构造(创建对象)
public Tax() {
}
//计费方法
public double price(Tax tax){
//不足3千米
if(tax.distance<=3){
if(tax.atNight){//黑夜
if(tax.time<20)//等待时间小于20分钟
return 8.0*1.5;
else
return 8.0*1.5+(int)(tax.time*0.5);
}else {
if(tax.time<20)//等待时间小于20分钟
return 8.0;
else
return 8.0+(int)(tax.time*0.5);
}
}
//行驶大于3千米
else {
if (tax.atNight) {//黑夜
if (tax.time < 20)//等待时间小于20分钟
return 8.0 * 1.5+(tax.distance-3)*1.5*1.5;
else
return 8.0 * 1.5+(tax.distance-3)*1.5*1.5 + (int) (tax.time * 0.5);
} else {
if (tax.time < 20)//等待时间小于20分钟
return 8.0+(tax.distance-3)*1.5;
else
return 8.0*(tax.distance-3)*1.5 + (int) (tax.time * 0.5);
}
}
}
public static void main(String[] args) {
Tax tax=new Tax();
tax.distance=7.1;
tax.atNight=false;
tax.time=0;
double price = tax.price(tax);
System.out.println(price);
}
}
测试结果如下
题目中的答案使用了四舍五入,真正答案就是上面的代码