/**题目:计算一下公用电话的电话费,规则如下:前3分钟一共0.2元,从第4分钟起,每一分钟0.1元 输入秒数,输出付费钱数。 不足一分钟的按一分钟收费。比如:输入190秒,收费=0.2+0.1=0.3元*/
下面写的代码,为何不对?怎么改正
import java.util.Scanner;
public class Day03txtHomework3 {
public static void main(String[] args){
Scanner console = new Scanner(System.in);
System.out.print("请输入秒数:");//从控制台输入一个秒数
int seconds = console.nextInt();
int minutes = seconds/60;//计算出分钟数
double pay = 0.0d; //定义费用paytes
System.out.println(minutes);
if(minutes<=3){
pay = 0.2d;
System.out.println("a");
}
else if(seconds%60!=0){
pay = 0.2d+(minutes -3.0)*0.1d+0.1d;
System.out.println("b");
}
else{
pay = 0.2d+(minutes -3.0)*0.1d ;
System.out.println("c");
}
System.out.println("收费="+pay);
}
}
thanks
------解决方案--------------------
- Java code
int seconds = console.nextInt();int minutes = seconds/60;//计算出分钟数if (second%60 != 0) minutes++; //如果不满整分钟,那么要补成整分钟,否则190秒就被当成整3分钟计算了if (minutes<=3) { pay = 0.2d;} else { pay = 0.2d + (minutes-3)*0.1d;}
------解决方案--------------------
处理小数用BigDecimal
- Java code
import java.math.BigDecimal;import java.util.Scanner;public class Day03txtHomework3 { public static void main(String[] args) { final int defaultSecond = 3 * 60; final BigDecimal defaultPay = new BigDecimal("0.2"); final BigDecimal extraPay = new BigDecimal("0.1"); //final double defaultPay = 0.2d; //final double extraPay = 0.1d; Scanner console = new Scanner(System.in); System.out.print("请输入秒数:");// 从控制台输入一个秒数 int seconds = console.nextInt(); BigDecimal pay; if(seconds <= defaultSecond) pay = defaultPay; else { int extraTime = (seconds - defaultSecond) / 60 + 1;//注意这里加1 pay = defaultPay.add(extraPay.multiply(new BigDecimal(String.valueOf(extraTime)))); } System.out.println("收费=" + pay.toString() +"元"); }}
------解决方案--------------------
int extraTime = (seconds - defaultSecond) / 60 + 1;//注意这里加1
LS这里不能直接+1,要判断能否被60整除,比如240秒,算下来是4分钟,也就是0.2+0.1费用,如果不判断内否被60整除就+1,那么变成extraTime=2分钟,这是不对的
------解决方案--------------------