我正在为学校做一个项目,要求我搬一个机器人.机器人每秒移动的距离(变量t)由下面的函数计算.
第一个功能很简单.第二个和第三个是我被卡住的地方.我怎么写F(t-1)?以下是我到目前为止的情况.
if (t == 0) {
distance = 2;
} else if (t > 0 && <=6 || t > 12) {
// No clue on how to write the 2nd distance equation.
} else if (t >= 7 && <=12) {
// No clue on how to write the 3rd distance equation.
}
Run Code Online (Sandbox Code Playgroud)
递归确实不是解决这个问题的必要条件.
请注意,在每个非零时间情况下,F(t) = F(t-1) + something.
所以你可以简单地做:
double f = 2; /* Initial value at t=0 */
for (int t = 1; t <= maxT; ++t) { // maxT is the maximum value of t.
if (t <= 6 || t > 12) {
f += /* something for case 2 */;
} else {
f += /* something for case 3 */;
}
}
System.out.println(f);
Run Code Online (Sandbox Code Playgroud)
你可以用递归来做到这一点,但你会得到一个StackOverflowErrorif maxT变得适度大; 相反,使用循环将适用于任意大maxT(模数浮点错误).
正如@Andreas指出的那样,你可以在不循环遍历所有值的情况下执行此操作t:
double f = 2 * (maxT + 1);
for (int t = 7; t <= maxT && t <= 12; ++t) {
f += log(t) - 2;
}
Run Code Online (Sandbox Code Playgroud)
并且您可以通过预先计算值来消除该循环.
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |