C ++矢量幅度

时间:2017-11-13 14:31:41

标签: c++ function math vector magnitude

我的任务是在C ++中创建一个矢量幅度函数作为类项目的数学库的一部分,但我不确定如何去做,如果有人可以推荐一些页面来阅读或给我一些帮助那会很棒

编辑:我的C ++知识并不是很好,我正在寻找帮助我学习如何为矢量做功能的页面

2 个答案:

答案 0 :(得分:3)

快速谷歌提出

magnitudes

由于这是一个课程项目,我将让您阅读链接,而不是在此提供详细信息。

您可能想要阅读使用向量,例如here

我个人更喜欢尽可能使用C ++标准算法。你可以使用std :: accumulate快速有效地完成这类工作。

#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>

int main()
{
    std::vector<double> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    double ssq = std::accumulate(v.begin(), v.end(),
                                    0.0,
                                    /* add here */);

    std::cout << "ssq: " << ssq << '\n';
}

标记为/* add here */的行是您需要添加运算符的位置,该运算符采用当前运行的平方和以及要添加的下一个值,并返回新的运行平方和。

或者,你可以写一个for循环

double ssq = 0.0;
std::vector<double> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto e : v)
{
    // calculate sum of squares here
}

答案 1 :(得分:0)

重温GCSE数学:

c² = a² + b²

double magnitude = sqrt((Vector.x*Vector.x) + (Vector.y*Vector.y));
相关问题