0

I created a little program that is supposed to calculate pi using the first 26 iterations of the Leibniz formula in c++, just to see id it would work. When I ran the code, it outputted 4 instead of a floating point number. What is going on and how can I fix it? Here is the code:

#include <iostream>
#include <math.h>
using namespace std;

int main ()
{
    float a = 1/1;
    float b = 1/3;
    float c = 1/5;
    float d = 1/7;
    float e = 1/9;
    float f = 1/11;
    float g = 1/13;
    float h = 1/15;
    float i = 1/17;
    float j = 1/19;
    float k = 1/21;
    float l = 1/23;
    float m = 1/25;
    float n = 1/27;
    float o = 1/29;
    float p = 1/31;
    float q = 1/33;
    float r = 1/35;
    float s = 1/37;
    float t = 1/39;
    float u = 1/41;
    float v = 1/43;
    float w = 1/45;
    float x = 1/47;
    float y = 1/49;
    float z = 1/51;

    float a1 = a-b+c-d+e-f+g-h+i-j+k-l+m-n+o-p+q-r+s-t+u-v+w-x+y-z;
    float b1 = a1*4;

    cout << b1;
}

Yes, I know there are much more simple ways to do this, but this is just a proof of concept.

Mr.666Man
  • 1
  • 1
  • 1

2 Answers2

7

When you use:

float b = 1/3;

the RHS of the assignment operator is evaluated using integer division, which results in 0. All other variables have the 0 value except a which has the value of 1.

In order to avoid that, use

float b = 1.0f/3;

or

float b = 1.0/3;

Make similar changes to all other statements.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Another way, use casting

float a = (float)1/1; // C-style cast

or

float a = float(1)/1; 
khôi nguyễn
  • 626
  • 6
  • 15