First, please use code tags when posting code. See
http://www.cplusplus.com/articles/jEywvCM9/
Your code (and some whitespace) in tags:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
using namespace std;
int main()
{
double i, n, sum=0, k=2, l=3, h=1;
cout << "Give the number n: \n";
cin >> n;
for ( i=1; i <= (3*n-2)/(3*n-1)*(3*n); i++ )
{
sum += h/(k*i);
h = h+3;
k = k+3;
l = l+3;
}
cout << "The sum of the numeric series is: " << sum;
return 0;
}
|
Okay, how many terms does the serie have?
Lets test:
On n==1, the last term is 1/(2*3). That is also the first term! One term in total.
On n==2, the last term is 4/(5*6). That is also the second term! Two terms in total.
Do you notice where this leads to?
There are n terms. Can you think of a much simple loop condition that gives you correct amount of terms?
Look at the equation on line 11. Is it an l or i in there? Which should it be?
Names of variables can be clear and descriptive, or mysterious and easy to typo.
You declare all variables in one statement. It is legal and compact, but can lead to errors.
You do use double values for everything. The division and sum do have to operate on floating point type (double), but the loop counter and h,k,l would be better as integers. Integers are exact, while floats are not always what we think them to be.
Have you seen:
1 2 3
|
int h=1,k=2,l=3;
double sum=0;
sum += static_cast<double>(h) / (k*l);
|
We convert the h into double value on the fly and that forces the entire division to use floating point math, but the h,k,l remain integers.
One could do the conversion differently:
1 2 3 4 5 6 7
|
int w;
double sum=0;
int z = 3*w;
int y = z-1;
double x = z-2
sum += x / (y*z);
|
What if the user gives 3.14 for n? How about -8? Or 0?
If n is integer, then the first won't be a problem; only the '3' is used.
The loop condition saves us from values <1, does it not?