Issue
I have the following vector values: [2, 3, 7]
.
I want to output the product of the vector, as in 2*3*7 = 42
.
I wrote some code for it but it doesn't appear to be working. I am new to C++, so I am not sure how to get the product of the values in a vector given any numeric vector of any size.
#include <bits/stdc++.h>
int main()
{
int n;
cin >> n;
vector<int> vec;
while (n--)
{
int temp;
cin >> temp;
vec.push_back(temp);
}
int total = 1;
total *= vec;
cout << vec << endl;
return 0;
}
Solution
If you want to get the product of any numeric vector of any size, here's a function that works with any numeric type of vector with the help of templates:
template <class any>
long double vectorProduct(vector<any> vec) {
long double total = 1;
for(any num : vec) {
total *= num;
}
return total;
}
Usage:
cout << vectorProduct(vec) << endl;
Answered By - Mystical Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.