分支-09. 分段计算居民水费

为鼓励居民节约用水,自来水公司采取按用水量阶梯式计价的办法,居民应交水费y(元)与月用水量x(吨)相关:当x不超过15吨时,y=4x/3;超过后,y=2.5x-17.5。请编写程序实现水费的计算。

输入格式:输入在一行中给出非负实数x

输出格式:在一行输出应交的水费,精确到小数点后2位。

输入样例1:12
输出样例1:16.00
输入样例2:16
输出样例2:22.50
import java.text.DecimalFormat;
import java.util.Scanner;

public class IO_1009 {
    public static void main(String[] args) {
        int x;
        double y;

        DecimalFormat df = new DecimalFormat("0.00");
        Scanner input = new Scanner(System.in);
        x=input.nextInt();
        if (x < 15)
            y = (double)(x) * 4 / 3;
        else
            y = 2.5 * (double)(x) - 17.5;
        
        System.out.println(df.format(y));
        input.close();
    }

}
import java.text.DecimalFormat;
import java.util.Scanner;

public class IO_1009 {
    public static void main(String[] args) {
        double x;
        double y;

        DecimalFormat df = new DecimalFormat("0.00");
        Scanner input = new Scanner(System.in);
        x=input.nextInt();
        if (x < 15)
            y = (x) * 4 / 3;
        else
            y = 2.5 * (x) - 17.5;
        
        System.out.println(df.format(y));
        input.close();
    }

}

以上两个别人写的都可以通过PAT。

下面是我自己写的却不行,提示“返回非零”,这是为什么呢??(下面有解答!)

import java.util.Scanner;
import java.text.DecimalFormat;  
public class Main 
{
    public static void main(String[] args)
    {
        double x,y; 
      DecimalFormat df = new DecimalFormat("0.00");
        Scanner input = new Scanner(System.in);
        x = input.nextDouble();/*可能是PAT用的测试数据是整数*/
      if(x <= 15)
            y = x * 4 / 3;    
    else 
            y = x * 2.5 - 17.5;
      System.out.print(df.format(y));   
    }
}

 

哈哈,其实上面的两个也是不完善的,当输入小数的时候就会报错。

修改正确的代码如下,可以满足输入非负实数(即:正整数,正小数):

import java.util.Scanner;
import java.text.DecimalFormat;  
public class Main 
{
    public static void main(String[] args)
    {
        DecimalFormat df = new DecimalFormat("0.00");
        Scanner input = new Scanner(System.in);
        String num = input.nextLine();/*输入字符串,下面转换成double类型*/
        double x = Double.parseDouble(num);
        double y; 
        if(x <= 15)
           y = x * 4 / 3;    
        else 
           y = x * 2.5 - 17.5;
        System.out.print(df.format(y));   
    }
}

 

posted @ 2014-09-16 12:51  winTeaer  阅读(1279)  评论(0编辑  收藏  举报