c++ - 有三角波函数吗?

标签 c++ loops for-loop geometry sine-wave

<分区>

for 循环中使用 % 得到一个 saw 函数,例如使用 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?

摘自诺多语答案:

三角波

y = abs((x++ % 6) - 3);

这给出了一个周期为 6 的三角波,在 3 和 0 之间振荡。

现在把它放在一个函数中:

int foo(int inputPosition, int period, int amplitude)
{
    return abs((inputPosition % period) - amplitude);
}

关于c++ - 有三角波函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28588292/

相关文章:

c++ - 使用 CMake 和 NMake 构建 OpenCV 3.0 时出现链接错误

c++ - 计算文本文件中每个单词的出现次数

在行和列中输出数字的 C++ 代码

python - 当项目已存在以及使用 for 循环时将其添加到列表中

actionscript-3 - for(const i)而不是(var i)

c++ - boost::optional 与 boost::make_optional

c++ - 在 C++ 中命名和使用迭代器的常规约定是什么?

java - 从 Java 数组中删除重复值的最优雅方法是什么

javascript - 我的 For 循环太快,我错过了获取关键数据的机会

javascript - 理解 javascript 中的 for 循环