用Java语言编写一个计算行李托运费的程序,当行李重量小于40公斤时费用为0,大于40公斤小于60公斤时,超出部分每公斤加收10元,大于60公斤小于80公斤时,超出部分每公斤加收20元,80公斤以上的部分,每公斤加收30元。求解托运行李重量为M时的应付的总费用。
import java.util.*;
public class xinglituoyun {
public static void main(String[] args) {
System.out.println("Please input the weight of package:");
Scanner sc=new Scanner(System.in);
int weight=sc.nextInt();
double total=0;
if(weight<=40) {
total=weight*0;
}
else {
if(weight>40||weight<=60){
total=((weight-40)*10);}
else{
if(weight>60||weight<=80){
total=(200+(total-60)*20);}
else{
total=(600+(total-80)*30);
}
}
}
System.out.println("Total:"+total);
}
}
在输入61的时候,结果是210 正确的应该是220
不满足weight>60||weight<=80的不应该运行的是里面一层if else嘛?
但是程序运行的是if那个weight>60||weight<=80,所以输出结果是210
这个问题的正确答案
变量用错了。
代码修改如下:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please input the weight of package:");
Scanner sc=new Scanner(System.in);
int weight=sc.nextInt();
double total=0;
if(weight<=40) {
total=weight*0;
}
else {
if(weight>40 && weight<=60){
total=((weight-40)*10);}
else{
if(weight>60 && weight<=80){
total=(200+(weight-60)*20);}
else{
total=(600+(weight-80)*30);
}
}
}
System.out.println("Total:"+total);
}
}
if(weight>40||weight<=60){
改为
if(weight>40&&weight<=60){
if(weight>60||weight<=80){
改为
if(weight>60&&weight<=80){
=====
否则你输入61,进入的是以下if语句代码块
if(weight>40||weight<=60){
total=((weight-40)*10);}
因为weight > 40成立了!!!
但if(weight>40 && weight<=60){ 是不成立的,就能进入else部分
Scanner scanner = new Scanner(System.in);
System.out.print("请输入您要托运行李的重量:");
Double weight = scanner.nextDouble();
Double money = 0D;
if (weight <= 40) {
} else if (weight <= 60) {
money = Double.valueOf((weight - 40) * 10);
} else if (weight <= 80) {
money = Double.valueOf((weight - 60) * 20 + 200);
} else if (weight > 80) {
money = Double.valueOf((weight - 80) * 30 + 600);
}
System.out.println("当前行李重量为" + weight + "公斤," + "托运行李的费用为" + money + "元");