0
// PI = 4 - (4/3) + (4/5) - (4/7) ... for 100 first statements
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
    double PI = 0.0;
    int a = 1;
    for (int i = 1; i <= 100; i++) {
        if (i % 2 == 1) {
            PI += double(4 / a);
        }
        else {
            PI -= double(4 / a);
        }
        a += 2;
    }
    cout << "PI Number is : " << PI;
    cout << endl;
    return 0;
}

I tried this code in visual studio 2015 to give me the answer of PI number value but it returns "PI Number is : 3" and I want it to return a float or a double number.

What should I do?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
coder boy
  • 17
  • 5

3 Answers3

3

In double(4 / a), the 4 / a part evaluates to an integer and it is already truncated by the time you cast it to double. What you want to do is 4.0 / a instead, and no need for an explicit cast.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
2

4 / a is an integer division and your conversion double(…) happens after that division, so the result will never have something after the decimal point. e.g. 4/5 results in 0.

You need to change 4 from an integer to a double 4.

t.niese
  • 39,256
  • 9
  • 74
  • 101
1

The issue in your code is when it's computing the value:

double PI = 0.0;
int a = 1;
for (int i = 1; i <= 100; i++) {
    if (i % 2 == 1) {
        PI += double(4 / a);
    }
    else {
        PI -= double(4 / a);
    }
    a += 2;
}

You shouldn't do double(4 / a) but rather (double)4 / a or 4.0 / a

double PI = 0.0;
int a = 1;
for (int i = 1; i <= 100; i++) {
    if (i % 2 == 1) {
        PI += (double)4 / a;
    }
    else {
        PI -= (double)4 / a;
    }
    a += 2;
}
Léolol DB
  • 313
  • 3
  • 15