C, Perl, and Python similar loops different results

Well, comparing your methods, it became obvious your final operation for calculating pi was incorrect.

Replace pi = (val + x) * (four/(long double)n); with these two lines:

val = val * (long double)2.0;
pi = (val + x) * ((long double)2.0/(long double)n);

Compiling and running gives:


Which I believe is the output you’re looking for.

Leave a Comment