这个问题在这里已有答案:
在for
循环中使用%
来获得锯功能,例如使用5个打印周期2个循环将如下所示:
for(auto i = 0; i < 5 * 2; ++i) cout << i % 5 << endl;
结果是:
0 1 2 3 4 0 1 2 3 4
我想要一个函数返回一个三角波,所以对于一些函数foo
:
for(auto i = 0; i < 5 * 2; ++i) cout << foo(i, 5) << endl;
会导致:
0 1 2 1 0 0 1 2 1 0
有这样的功能,还是我需要拿出自己的功能?
看起来这里回答了一个非常相似的问题:Is there a one-line function that generates a triangle wave?
取自Noldorin的回答:
三角波
y = abs((x++ % 6) - 3);
这给出了周期6的三角波,在3和0之间振荡。
现在把它放在一个函数中:
int foo(int inputPosition, int period, int amplitude)
{
return abs((inputPosition % period) - amplitude);
}
你必须自己做:
// Assumes 0 <= i < n
int foo(int i, int n) {
int ix = i % n;
if ( ix < n/2 )
return ix;
else
return n-1-ix;
}
我认为在这个问题关闭之前我们至少应该在这里发布正确答案,因为它是重复的。
int foo(const int position, const int period){return period - abs(position % (2 * period) - period);}
然而,这给出了一个三角波,范围从[0,period
]和2 * period
的频率,我想要一个范围从[0,period / 2
]和period
的循环。这可以通过将一半的时间段传递给foo
或通过调整函数来实现:
int foo(const int position, const int period){return period / 2 - abs(position % period - period / 2);}
使用这样一个简单的函数内联似乎更可取,但我们的最终结果将是:
for(auto position = 0; position < 5 * 2; ++position) cout << 5 / 2 - abs(position % 5 - 5 / 2) << endl;
产生要求:
0 1 2 1 0 0 1 2 1 0