循环练习有三个参数

时间:2016-11-12 00:14:04

标签: java loops

我遇到了以下问题而且遇到了困难。我定义了三个变量,但是使用循环我应该能够使这个工作。任何帮助将不胜感激。

  

远程跑步者通过爬山来建立力量和耐力。这是一个由三个整数参数确定的山地锻炼的想法:x,y和n。第三个参数n是从山脚到顶部的英里距离。跑步者从底部开始。想法是跑上x英里然后立即转身并向下跑20英里,重复这个过程直到到达顶部。编写一个程序,提示用户输入x,y和n,然后输出在锻炼期间运行的总距离,计算上坡部分和下坡部分。

1 个答案:

答案 0 :(得分:0)

所以,我的总体想法看起来像这样。注意:未经测试。

public void runDistance(int x, int y, int n) {
    int distanceRun = 0;
    int elevation = 0;


    //Takes us to one run shy of the top of the hill
    while(elevation+(x) < n) {
        elevation+=(x-y);
        distanceRun+=x+y;
    }


    //adds the last bit of distance to the top of the hill (since we won't be running back down again)
    //We don't want to add the full x distance because that might be more than the hill. We just want to add what's left.
    if(elevation < n) {
        distanceRun+=(n-elevation);
    }


    System.out.println("Total distance run: " + distanceRun);


}