I'm trying to write a code in c to approximate the value of pi using a while loop. I know it is much easier to do so with a for loop but I'm trying to do so using while. the formula I'm using to do so is in link below: https://www.paulbui.net/wl/Taylor_Series_Pi_and_e and the code I wrote looks like this:
#include <stdio.h> #include <math.h> int main(){ long n=10; while(n>0){ double a=0; a+=((pow(-1,n))/((2*n)+1)); n=n-1; printf("%ld",4*a); } return 0; } the reason I used long and double type is that I wanted to do the approximation to a good preciseness but first I should do st for this problem. thanks in advance.
ato 0 on every iteration of the loop?double a=0;in each iteration. Do this before your start the loop. Also it is very uncommon to start the sum from highest value. Finally: The sum should go fromn=0, 1, 2....while you excluden==0doubleis%f.(pow(-1,n)is a terrible idea... The idiomatic way if to initialize aint coeff=1;and then in the loop usecoeff = -coeff;. Much simpler...