我已经考虑这个问题几个小时了,但似乎找不到可行的解决方案。
我有这段代码,理论上可以无限长:
y(1) = x(1)*h(1);
y(2) = x(1)*h(2)+x(2)*h(1);
y(3) = x(1)*h(3)+x(2)*h(2)+x(3)*h(1);
y(4) = x(1)*h(4)+x(2)*h(3)+x(3)*h(2)+x(4)*h(1);
y(5) = x(1)*h(5)+x(2)*h(4)+x(3)*h(3)+x(4)*h(2)+x(5)*h(1);
y(6) = x(2)*h(5)+x(3)*h(4)+x(4)*h(3)+x(5)*h(2)+x(6)*h(1);
y(7) = x(3)*h(5)+x(4)*h(4)+x(5)*h(3)+x(6)*h(2);
y(8) = x(4)*h(5)+x(5)*h(4)+x(6)*h(3);
y(9) = x(5)*h(5)+x(6)*h(4);
y(10) = x(6)*h(5);
为了最大限度地减少写入工作量并使其普遍适用,我想将其放入(可能?)两个循环中,但我不知道该怎么做。也许是两个带有动态计算变量的 for 循环?但话又说回来,我不知道如何实现它。
最佳答案
解决这个问题很有趣!
Note 对其进行了测试,似乎工作正常。使用我使用的 x 和 h,我的结果是: y(1) = 6
y(2) = 17
y(3) = 34
y(4) = 58
y(5) = 90
y(6) = 115
y(7) = 116
y(8) = 106
y(9) = 84
y(10) = 49
void DoCalcs () {
for (int i = 1; i <= 10; i++) {
int result = Y (i);
}
}
int Y (int i) {
//calculate start index for x
int xIndex = Math.Max (1, i - 4);
//calculate end index for x
int endXIndex = Math.Min (6, i);
//running sum
int totalresult = 0;
//loop through h until reaches zero, or until we run out terms in the sum
for (int startHIndex = Math.Min (5, i); startHIndex >= 1; startHIndex--) {
totalresult += X (xIndex) * H (startHIndex);
xIndex++;
//if we run out of terms, break out and return result
if (xIndex > endXIndex) {
return totalresult;
}
}
//otherwise return error
return -9999;
}
int X (int i) {
return i + 1;
//this could be whatever
}
int H (int i) {
return i + 2;
//this could be whatever
}
希望对您有所帮助!
编辑: 如果您需要让它继续无穷大,只需删除 breakout return 语句,并在最后返回总数。
关于java - 如何将其放入循环中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37304571/