简体   繁体   中英

How to write a separate function that computes scalar product?

I am aware there exists a C++ function template (std::inner_product), but I want to try writing my own. Here's some code I found but it runs in the main function:

#include <iostream>
using namespace std;
int main(){

   float vectorA[3], vectorB[3], scalar=0.0;
   int i;

   // Get input vectors from user.
   cout << "Enter elements of first vector: " << endl;
   for(i=0;i<3;i++)
   {
      cin >> vectorA[i];
   }
   cout << "Enter elements of second vector: " << endl;
   for(i=0;i<3;i++)
   {
      cin >> vectorB[i];
   }

   // Calculate scalar product.
   for(i=0;i<3;i++)
   {
      scalar = scalar + (vectorA[i] * vectorB[i]);
   }

   // Output result.
   cout << "The scalar product is " << scalar << endl;
   return 0;
}

Next, I want to write this into a separate reusable function that I can call from my main loop. This is the best I could come up with.

float scalarProduct(float a1, float a2, float a3, float b1, float b2, float b3) {

    float vectorA[3], vectorB[3], scalar;
    vectorA[0]=a1;
    vectorA[1]=a2;
    vectorA[2]=a3;
    vectorB[0]=b1;
    vectorB[1]=b2;
    vectorB[2]=b3;

    for(int i=0;i<3;i++)    // Calculate scalar product.
    {
        scalar = scalar + (vectorA[i] * vectorB[i]);
    }
    return scalar;
}

int main() {
    cout << scalarProduct(1,2,3,4,5,6);
}

So my questions are:

  1. How can I pass an array into this function? There must be a better way than having six parameters but I can't figure out how.
  2. When I run the program in Xcode, I get the warning 'Variable scalar may be uninitialised when used here' at the line

     scalar = scalar + (vectorA[i] * vectorB[i]); 

    The program still runs and computes the correct answer but how can I make this warning go away?

  1. How can I pass an array into this function? There must be a better way than having six parameters but I can't figure out how.quote

To pass an array into your function, simply do:

float scalarProduct(float arr[6])

In your main() , it will look like:

float array[6] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
cout << scalarProduct(array);

From there you can use your array like:

vectorA[0]=arr[0];
vectorA[1]=arr[1];
vectorA[2]=arr[2];
vectorB[0]=arr[3];
vectorB[1]=arr[4];
vectorB[2]=arr[5];
  1. When I run the program in Xcode, I get the warning 'Variable scalar may be uninitialised when used here' at the line

Maybe try and initialize scalar with an initial value:

float scalar = 0.0;

Question

How can I pass an array into this function? There must be a better way than having six parameters but I can't figure out how.

  1. Change the function to accept two arrays as argument. For the sake of safety, also pass the number of elements in the array.

     float scalarProduct(float a[], float b[], size_t num); 
  2. Change the function to accept two std:vector s as argument.

     float scalarProduct(std::vector<float> const& a, std::vector<float> const& b); 
  3. Change the function to accept two std:array s as argument.

     float scalarProduct(std::array<float, 3> const& a, std::array<float, 3> const& b); 

In all of these cases, you can access the elements of the collection using the array syntax.

float scalarProduct(std::array<float, 3> const& a, std::array<float, 3> const& b)
{
   // Initialize scalar to 0
   float scalar = 0.0f;
   for(int i=0;i<3;i++)    // Calculate scalar product.
   {
      scalar = scalar + (a[i] * b[i]);
   }
   return scalar;
}

The implementations will be a little different if you use the other signatures but not too different.

Question

When I run the program in Xcode, I get the warning 'Variable scalar may be uninitialised when used here' at the line

I have already added the line to initialize scalar . Without that, the initial value of scalar is not predictable. Also, accessing the value of an uninitialized variable is cause of undefined behavior.

Just have your function take in a reference to a vector (or array as stated by Hayden). A vector is better as you don't have to hard-code the size of the vector. Also, it is useful to have a template function for this case.

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
T scalarProduct(const vector<T>& a, const vector<T>& b)
{
    // Check that the size of a and b match here.
    // If not, do what you deem is necessary.

    T product = 0;  // Not initializing variable is cause of your warning.
    for (int i = 0; i < a.size(); i++)
        product += a[i] * b[i];

    return product;
}

int main(void)
{
    // Compile for c++ 11
    // vector<float> a = {1.0, 2.0, 3.0};
    // vector<float> b = {1, 1, 1};

    // Else
    vector<float> a;
    vector<float> b;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);
    b.push_back(1);
    b.push_back(1);
    b.push_back(1);

    cout << scalarProduct<float>(a, b) << endl;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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