简体   繁体   English

用C ++编写程序,我需要帮助

[英]Writing a program in C++ and I need help

So I am a new to this. 所以我是新手。 I am trying to write a program with a function 我正在尝试编写具有功能的程序

double_product(vector< double > a, vector< double > b) that computes the scalar product of two vectors. double_product(vector <double> a,vector <double> b)计算两个向量的标量积。 The scalar product is 标量积为

$a_{0}b_{0}+a_{1}b_{1}+...a_{n-1}b_{n-1}$. $ A_ {0} B_ {0} + A_ {1} B_ {1} + ... A_ {N-1} {B_ N-1} $。

Here is what I have. 这就是我所拥有的。 It is a mess, but I am trying! 这是一团糟,但我正在尝试!

#include<iostream>

#include<vector>

using namespace std;

class Scalar_product
{

public:

    Scalar_product(vector<double> a, vector<bouble> b);

};


double scalar_product(vector<double> a, vector<double> b) 
{

   double product = 0;

   for (int i=0; i <=a.size()-1; i++)

       for (int i=0; i <=b.size()-1; i++)

           product = product + (a[i])*(b[i]);

   return product;

}

int main()
{

    cout << product << endl;

    return 0;

}

You have a pretty correct idea, at the fundamental level. 从根本上来说,您有一个非常正确的想法。 A couple of basic building blocks extra and you'll be well on your way. 另外几个基本的构建基块,您将一路顺风。 Your scalar_product function is close, but not quite. 您的scalar_product函数接近,但不完全相同。 You've created two loop iterators with the same name iterating over the same values. 您已经创建了两个具有相同名称的循环迭代器,它们迭代相同的值。 It should be fine to simply say 简单地说就好了

if (a.size() != b.size()) {} // error
for (int i=0; i < a.size(); i++)
   product = product + (a[i])*(b[i]);

Now all you have to do is get some data, call it, and then output the result. 现在,您要做的就是获取一些数据,调用它,然后输出结果。

int main() {
    std::vector<double> a;
    std::vector<double> b;
    // fill with the values
    std::cout << scalar_product(a, b) << endl;
}

The whole class thing is completely unnecessary here- the only classes you need come in the Standard lib. 这里,整个class完全没有必要-您所需的唯一类是Standard库。

since I cannot comment I am forced to reply. 由于我无法发表评论,因此我不得不回覆。

apparently there is exactly the same question, word by word , here: 显然这里有一个词一个词完全一样的问题

Computing the scalar product of two vectors in C++ 用C ++计算两个向量的标量积

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM