美文网首页
兔子和萝卜问题

兔子和萝卜问题

作者: 瓶子卞凯 | 来源:发表于2017-01-10 17:54 被阅读0次

    题目:

    有100个萝卜,一只兔子边背边吃,走一米吃一个,走到家剩下多少萝卜,(到家一共50米,兔子每次只能背50个)。

    假设:

    兔子行动距离是离散的,即最小行动单位是1米。

    代码实现:

    package CarrotAndRabbit;

    public class CarrotAndRabbitForDiscrete {

    privateintcarrots= 0;

    privateintdistance= 0;

    privateintcapacity= 0;

    privateintcarrots_rest= 0;

    privateintdistance_rest= 0;

    public CarrotAndRabbitForDiscrete(intcarrots,intdistance,intcapacity) {

    this.carrots=carrots;

    this.distance=distance;

    this.carrots_rest=carrots;

    this.distance_rest=distance;

    this.capacity=capacity;

    }

    public int results() {

    while(distance_rest> 0){

    this.forwardOneMeter();

    }

    return this.carrots_rest;

    }

    public void conditions(){

    System.out.println("Distance: "+distance+" ,Carrots: "+carrots);

    }

    private void forwardOneMeter() {

    intmax_num= 0;

    intdiscard_carrots= 0;

    if(carrots_rest%capacity> 2){

    max_num=carrots_rest/capacity+ 1;

    }else{

    max_num=carrots_rest/capacity;

    discard_carrots=carrots_rest%capacity;

    }

    this.carrots_rest-=discard_carrots;

    if(max_num< 1) {

    this.carrots_rest= 0;

    this.distance_rest= 0;

    }elseif(max_num== 1) {

    this.carrots_rest--;

    this.distance_rest--;

    }else{

    this.carrots_rest=this.carrots_rest- 1 - (max_num- 1) * 2;

    this.distance_rest--;

    }

    //System.out.println(carrots_rest + ":" + distance_rest);

    }

    public static void main(String...strings) {

    CarrotAndRabbitForDiscretecarrotAndRabbit=newCarrotAndRabbitForDiscrete(100, 50, 50);

    System.out.println(carrotAndRabbit.results());

    }

    }

    相关文章

      网友评论

          本文标题:兔子和萝卜问题

          本文链接:https://www.haomeiwen.com/subject/utgkbttx.html