Program to calculate 1/3^1 + .... + 1/3^n

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aimi95
    New Member
    • May 2014
    • 4

    Program to calculate 1/3^1 + .... + 1/3^n

    Hello, I'm trying to make a C++ program which calculates the following series:

    1/3^1 + 1/3^2 + .... + 1/3^n

    So far I've tried this
    Code:
    #include<iostream>
    using namespace std;
    
    void main()
    {
    
    int z=1, n, n2;
    float num=1/3, sum=0;
    
    
    cout<<"n= ";
    cin>>n;
    
    while(n > 0)
    {
        z=1;
    	
    	n2 = n;
        while(n2 > 0)
    	{
    	    z = num * z;
    		n2--;
    	}
    	sum = z + sum;
    	n--;
    }
    cout<<endl<<sum;
    }
    but it always returns zero. Any help would be appreciated.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Code:
    float num=1/3 etc....
    So, 1/3 is 0 because there are no threes in 1.

    Don't mix integer arithmetic with floating point.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Just to be clear the problem in

      Code:
      float num=1/3, sum=0;
      Is that 1 and 3 are both integer constants so the calculation is done in integer arithmetic which drops all decimal places therefore 1/3 = 0.

      This is easy to fix by forcing 1 or both of the constants to be floating point constants by adding the decimal, the sum will then be calculated using floating point arithmetic and you will get the expected result

      Code:
      float num=1/3., sum=0;
      (Note I added a . the decimal point). Of course by default floating point constants have type double and you are using float. Normally it is best to keep your types the same to prevent conversion although strictly the compiler does all floating point calculations as double and the converts down to float anyway.

      Normally we would also say don't bother using float use double unless you have a particularly low memory platform. but if you did want to specify constants with type float you would do it like this

      Code:
      float num=1.F/3.F, sum=0;

      Comment

      Working...