Hi , I'm new to c programming. I have been giving a task to do and I got trouble in my code.
Can someone have a look my code and give me some advice?
The task is this:
(pi^2)/16 = (-1)^k /k+1 (1 + 1/3 + 1/5 +...+ 1/(2k+1))
Write a program which computes and prints an approximation of pi using a finite number of terms from the above formula. The number of terms must be input from the keyboard (via scanf ). The program must also print an approximation error: the difference between the approximation and the value of stored in the macro constant M_PI, defined in <math.h>.
Please start you program from
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
and this is what I wrote:
I'm getting this:
When I put any value, I'm still getting this.
I'm not sure where did the code went wrong.
So can I get some help?
thanks
Can someone have a look my code and give me some advice?
The task is this:
(pi^2)/16 = (-1)^k /k+1 (1 + 1/3 + 1/5 +...+ 1/(2k+1))
Write a program which computes and prints an approximation of pi using a finite number of terms from the above formula. The number of terms must be input from the keyboard (via scanf ). The program must also print an approximation error: the difference between the approximation and the value of stored in the macro constant M_PI, defined in <math.h>.
Please start you program from
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
and this is what I wrote:
//*pi^2 / 16 = (-1)^k / k(k+1) (1 + (1/3) + (1/5) + ... + ( 1/((2*k)+1)))*\\ #include <stdio.h> #include <math.h> #ifndef M_PI #define M_PI 3.1415926535897932384626433832795 #endif int main() { int k, i; double sum = 0; printf("Enter number of terms: "); scanf("%d",&k); for (i=1; i<=k; i++) { if (i %2 == 0) sum += (1.0) /(i+1); else sum -= (1.0) /(i+1); } printf("pi = %g\n\n", sqrt(16*sum)); system("pause"); }
I'm getting this:
Enter number of terms: 2 sqrt: DOMAIN error pi = +NAN
When I put any value, I'm still getting this.
I'm not sure where did the code went wrong.
So can I get some help?
thanks