We are suppose to get a sum series but I am running into a problem.
1/n + 2/n-1 + 3/n-2 ...n/1 is the sum she wants
My for loop is not right and I can't figure out why The answer is suppose to be 8.70 but I get 27.
#include <iostream>
using namespace std;
int main()
{
int n=5;
float sum=0;
for(int i=1; i<=n; i++){
for(int j =n; j>0; j--){
sum += i/j;
}
}
cout<<"Sum : "<<sum;}
You are using two loops to compute the sum while the series sum can be computed by a single loop. That should be a red flag.
Also, you are using integer division. That's going to give you wrong results.
Use:
#include <iostream>
using namespace std;
int main()
{
int n=5;
float sum=0;
for(int i=1; i <= n; i++)
{
sum += i*1.0f/(n - i + 1);
}
cout<<"Sum : "<<sum;
}