问题:一个井深10米,青蛙每天向上爬3米,晚上向下滑2米,多少天可以爬出去?
代码示例:
public class Well
{
//井深
public static int WellDepth = 2;
//每天向上爬
public static int up = 3;
//晚上向下滑
public static int down = 2;
public static void main (String[] args)
{
int up = Well.upWell (0, 0);
System.out.println (up);
}
private static int upWell (int high,int day)
{
//增加1天
day++;
//向上爬
high = high +up;
//如果已经爬出去,就不存在想下滑
if(high >= WellDepth){
return day;
}else{
//向下滑
high = high - down;
return upWell (high,day);
}
}
}
注意点:到最后一天的时候,青蛙已经爬出井,因此不会再往下滑。