如何用java模数?

时间:2017-06-29 09:32:26

标签: java division modulus divide

前300米是20费,接下来200米是2费。 我想以米为单位计算距离。

输入: 300 输出: 20

输入: 500 输出: 22

输入: 700 输出: 24

public static void main(String [] args){
    Scanner sc = new Scanner(System.in);
    System.out.println("Input the distance in Meters: ");
    int getInput = sc.nextInt();

    double first = 20.00; //first 300 meters
    double second = 2.00; //every 200 meters

    if(getInput <= 300){

        System.out.println("Your trip fee is: " + first);

    }
    else if(getInput >= 300){
        double fee = getInput / 300;
        double tFee = fee * first;

        double remainder = getInput % 300;
        double output = remainder / 200;
        double fees = output * second;

        double totalFee = tFee + fees;

        System.out.println("Your trip fee is: " + totalFee );

    }else{


        System.out.println("i du nu!");

    }
}

我需要算法,我的思绪被卡住了。我已经使用了if else语句。

2 个答案:

答案 0 :(得分:0)

我们不应该为您编码,但这里的算法可能对您有所帮助。但试着理解然后实施:

if(input <= 300)
{
    output = 20;
}
else if(input > 300)
{
    extra = input - 300;

    if(extra%200 == 0)
    {
        output =  20 + (2*(extra/200));
    }
    else
    {
        output = 20 + (2*(extra/200)) + 2;
    }
}

答案 1 :(得分:0)

根据您的需要,我认为有三种选择。 一个包含所有三个的示例程序:

    public static void main(String [] args){
//        Scanner sc = new Scanner(System.in);
//        System.out.println("Input the distance in Meters: ");
//        compute(sc.nextInt());

        System.out.println("input: 300");
        compute(300);
        System.out.println("input: 500");
        compute(500);
        System.out.println("input: 550");
        compute(550);
        System.out.println("input: 700");
        compute(700);
    }

    private static void compute(int input) {

        int output = 20 +  ((input - 300) / 200) * 2;
        System.out.println("Result A: " + output);

        double outputB = 20.0 +  ((input - 300.0) / 200.0) * 2.0;
        System.out.println("Result B: " + outputB);

        int outputC = 20 + (int)Math.ceil((input - 300.0) / 200.0) * 2;
        System.out.println("Result C: " + outputC);
    }

有了这些结果:

input: 300
Result A: 20
Result B: 20.0
Result C: 20
input: 500
Result A: 22
Result B: 22.0
Result C: 22
input: 550
Result A: 22
Result B: 22.5
Result C: 24
input: 700
Result A: 24
Result B: 24.0
Result C: 24