我遇到了以下问题,并且遇到了困难。我定义了三个变量,但是使用循环应该可以完成这项工作。任何帮助,将不胜感激。
越野跑者通过爬坡来增强力量和耐力。这是一个由三个整数参数(x,y和n)确定的山坡锻炼的想法。第三个参数n是从山底到山顶的距离(以英里为单位)。跑步者从底部开始。这个想法是先跑x英里,然后立即转弯再跑y英里,重复此过程直到到达顶点。编写一个程序,提示用户输入x,y和n,然后输出在锻炼过程中将要跑步的总距离,同时计算上坡部分和下坡部分。
所以,我的总体想法是这样的。注意:未经测试。
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句