兔子和萝卜问题

题目:

有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());

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Java经典问题算法大全 /*【程序1】 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子...
    赵宇_阿特奇阅读 1,916评论 0 2
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,767评论 18 399
  • 【程序1】 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔...
    叶总韩阅读 5,166评论 0 41
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,969评论 19 139
  • 我们在一起,仅仅是因为我快乐你也快乐,如果有一天,你或我没有这份快乐了,请免除那些无聊的猜忌、争吵。好聚;好散。
    乍暖还凉0123阅读 154评论 0 0