0

I am trying to make a simple pi calculator in cpp but when I try to run it it only prints out 3. this is my code:

#include <iostream>

using namespace std;

double pi = 0.0;
long unsigned int d = 1;

int main() {
  while (true) {
        pi += (4/d) - (4/ (d+2));
        d += 4;

        cout << pi << endl;
  }
}

I'm relatively inexperienced with c++ so please help.

Kozyn
  • 11
  • 1
  • for d use a float (or double) – PapaAtHome Oct 07 '22 at 11:46
  • and add .0 after the constants – akira hinoshiro Oct 07 '22 at 11:46
  • You are dividing two integer numbers (`4/d`) which results in an integer, which doesn't keep the fractional part. To make it cast implicitly into a double, write `4.0` instead of `4` – Sewbacca Oct 07 '22 at 11:47
  • 4
    First thing to be aware of is that C++ `/` performs *integer division* so an expression such as `4/5` produces `0` and `8/7` produces `1`, *etc*. While you have declared `pi` to be a double the *rhs* of the assignment to `pi` is pure integer arithmetic. – High Performance Mark Oct 07 '22 at 11:48
  • @HighPerformanceMark: `4/7==1`? The result is 3 because `4/1 - 4/(1+2)==3`, the first two terms. All subsequent terms starting with `4/5` are 0. – MSalters Oct 07 '22 at 11:51
  • @HighPerformanceMark the statement about `/` is kinda misleading, `1/2.0F` for example results in `0.5F` https://en.cppreference.com/w/cpp/language/operator_arithmetic#Conversions – Yamahari Oct 07 '22 at 11:57
  • 1
    Indeed, a sufficient fix is to replace `4` with `4.0` here. That will already trigger Floating Point (FP) division. – MSalters Oct 07 '22 at 11:59
  • 1
    @Sewbacca -- technical point: there is no such thing as an implicit cast. A cast is something you write in your source code to tell the compiler to do a conversion. So it's always explicit. You're right about how to fix the problem: "To make it **convert** implicitly into a double...". – Pete Becker Oct 07 '22 at 13:27

0 Answers0