Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 有三角波函数吗?_C++_Loops_For Loop_Geometry_Sine Wave - Fatal编程技术网

C++ 有三角波函数吗?

C++ 有三角波函数吗?,c++,loops,for-loop,geometry,sine-wave,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 1 0 0 1 2 1 0 有这样的功能吗,或者我需要自己设计吗?你必须自己设计: // Assumes 0 <= i < n int foo(int i, int n) { int ix = i % n; if ( ix

for
-循环中,使用
%
获得saw功能,例如,使用5个打印周期,2个周期如下所示:

for(auto i = 0; i < 5 * 2; ++i) cout << i % 5 << endl;
将导致:

0
1
2
1
0
0
1
2
1
0


有这样的功能吗,或者我需要自己设计吗?

你必须自己设计:

// 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;
}

//假设0看起来像是一个非常相似的问题在这里得到了回答:

摘自诺尔多林回答:

三角波

y = abs((x++ % 6) - 3);
这将产生周期为6的三角波,在3和0之间振荡

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

int foo(int inputPosition, int period, int amplitude)
{
    return abs((inputPosition % period) - amplitude);
}
int foo(const int position, const int period){return period / 2 - abs(position % period - period / 2);}

我想我们至少应该在这个问题结束之前把正确答案贴在这里,因为它是重复的

是正确的

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(int inputPosition, int period, int amplitude)
{
    return abs((inputPosition % period) - amplitude);
}
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;

for(auto position=0;position<5*2;+++position)可能看起来像
abs(((i+2)%5)-2)
,但它给出了0 1 2 1 0 1 2…你的函数有点奇怪,兄弟。它不仅无法接受我在问题中指定的输入,而且无法编译,因为
x
未定义。无论如何,我在找到那个复制品方面做得很好。是的,我在读你的评论之前就注意到了这一点。我编辑了它,现在应该可以修复了。走近一点,它仍然与问题中指定的签名不匹配,但它现在可以编译了。(我知道我们都可以暗示你在
foo
中应该做什么,但我们也可以遵循的链接,并从那里暗示一个
foo
。如果你要使用其他人的解决方案来回答这个问题,你至少应该根据实际问题定制他们的答案。)对不起,赛博发布链接时,我已经在写答案了。我不仅仅是从他那里拿走的。在问问题之前,你可能应该在谷歌上搜索2秒钟。因为我自己花了这么长时间才找到那个链接。我相信你是对的,我应该花更多的时间来研究,我的错误。无论如何,回到这个答案上;靠近右边,看一看,这就是你要复制的。