I'm quite new to c++ and I'm having trouble with this. It shows the correct sum but the product isn't.
The user specifies how many numbers they'll enter, enters the numbers, the program then prints out the sum and product of all the numbers entered.
What seems to be its problem?
Here's the code:
#include <iostream>
using namespace std;
int main()
{
int arr[20],i,n,sum=0,product=0;
cout<<"How many elements you want to enter?: ";
cin>>n;
cout << "Please enter " << n << " values to find their sum and product" <<endl;
for(i=0;i<n;i++)
{
cin >> arr[i];
cout << "value #" << i << ": " << arr[i] << " entered." << endl;
}
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
for(i=0;i<n;i++)
{
product=product*arr[i];
}
cout<<"Sum is "<<sum<<endl;
cout<<"Product is "<<product;
return 0;
}
What you have is a simple mathematical error. You declared the product
variable to 0, anything multiplied by 0 is equivalent to 0, if you change the value of product
to 1, it will solve your issue.
First, you your mistake is that you initialize the product with 0. Besides, here is an "elegant" way to add and multiply elements of array using c++ algorithms:
#include<functional>
#include<numeric>
#include<vector>
using namespace std;
int main(){
vector<int> nums = { 1,2,3,4,5 };
vector<int> sums(nums.size(), 0);
vector<int>products(nums.size());
std::partial_sum(nums.begin(), nums.end(), sums.begin());
std::partial_sum(nums.begin(), nums.end(), products.begin(), std::multiplies<int>());
}
Now the elements of vector sums
contain the running sum of the nums
vector: 1, 3, 6 ,10, 15 And the elements of products
vector contain running products: 1, 2, 6, 24, 120
变量product
被初始化为0,因此任何与它相乘的乘积也将为0。将其初始化为1,即乘法的中性元素,您应该得到正确的结果。
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.