Home > OS >  How do I do a summation in C without math.c?
How do I do a summation in C without math.c?

Time:11-09

Hello I need to create this summation and if you put the number 30000 the response should the number of pi, however it's not working here's the summation and here's the code.

enter image description here

#include <stdio.h>  
#include <stdlib.h> 
#include <string.h> 
#include <time.h>   
#include <limits.h> 
#include <ctype.h>  
#include <stdbool.h>

int main( void ){

int num, k;
double pi= 0;

printf("Digite o total de termos >=30000: ");
scanf("%d", &num);
if (num < 30000){
    printf("Erro.");
    
}else {
    for (k = 1; k<= num; k  ){
        if (k % 2 == 0){
            pi = (double)(-1)/ (2*k -1);
            
            
        }else{
            pi =  (double)(1)/ (2*k -1);
        
           
        }
        pi = pi * 4;
    }
   
    printf("O valor de pi e %f", pi);
    
    
}



return 0; }

CodePudding user response:

Here is a general way to sum things up:

double sum(int from, int to, double (*f)(int)) {
    double ret = 0.0;

    for(int i=from; i<to; i  )
        ret =f(i);

    return ret;
}

And then you can write this function:

double fun(int current) {
    double sign = current %2 == 0 ? -1.0 : 1.0;
    return sign / (2*current - 1)
}

Finally, call it like this:

double pi = sum(1, num, fun);

Do note that this is probably not a good way to go if you're a beginner student that is looking for a solution to some homework.

CodePudding user response:

#include <stdio.h>

int main(void) {
    double pi=0;
    
    for(int k=1; k<=3000;   k)
    {
        pi  = (2.*(k%2)-1) / (2*k-1);   // This line does a summation, and uses floating point math (Not Integer Math)
    }
    
    printf("Pi : %f\n", 4*pi);
    return 0;
}
  •  Tags:  
  • c
  • Related