//Write a C++ program to determine and print the sum of the series ( 1/6 + 1/10 + 1/14 + … + 1/(2*(2*n+1)) )for a given value of n. The value of n should be given interactively through the terminal. (Note: You will only get credit if you use a loop!)

so i have to find the sum and i have tried it for a while and i cant get it. im using this code and it works good if the series was (6+10+14+...+(2*(2*n+1)) ), but as soon as i try to put "1/(2*(2*n+1)) " i get a zero as the answer. i know its something simple since we are not that advanced in class but i still cant find it. thank you very much for any help.

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

int iCount = 0, iMax = 0;
float iAns = 0;

cout << "Enter a positive integer for n:" << endl;
cin >> iMax;

for( iCount=1; iCount <= iMax; iCount++ )
{
iAns = iAns + 2*((iCount*2)+1) ; // the 2*((iCount*2)+1) works if the series was (6+10+14+...), and as soon as i put a 1/ in front of it instead of giving me the right answer it gives me 0.

}
cout << "The sum of this series is: " << iAns << endl;

return 1;
}

I'd suggest printing the sum at each iteration of the loop to see what is happening. If you can't get it, post code without any user input that produces a result that you are not expecting.

You have made the classic error, that always seems to trip up beginners: That is if you use integers, then you get integer arithmetic :

Consider this code:

std::cout<<"1/4 == "<<1/4<<std::endl;

That will print the unexpected value: 0. That is because 1 and 4 are both integers and fractions cannot be represented in an integer value, therefore they are truncated.

In you code you sum up the result into a float. This does not help:

float F=1/4; 
std::cout<<"Look f is still 0 == "<<F<<std::endl;

That is because the division is done before the conversion type is examined.

However, this is different:

float F=1.0/4;

Since 1.0 is a double and the integer is converted into the double.

So in short use 1.0 instead of 1.

The way you are doing it says int/int*(int*int)+int you want everything multiplied to be a float otherwise it converts it to an int.

1/2 gives the answer 0 because integers do not have decimals.
1.0/2.0 gives the answer 0.5 because doubles/floats do have decimals.

So the way to write what you want is 1.0/float(2*(iCount*2+1));

Since you know that iCount is always an integer you dont have to multiply by a float or add by a float but you have to convert all that into a float and put it under 1.0

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.