1
Good evening, I’m having the following problem, I’m developing an algorithm to calculate a pi approximation.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <locale.h>
int mmc(int num1, int num2) {
int mmc, aux, c;
if(num2==1)mmc=num1;
else{
for (c = 2; c <= num2; c++) {
aux = num1 * c;
if ((aux % num2) == 0) {
mmc = aux;
c= num2 + 1;
}
}
}
return mmc;
}
double R1(int num){
int cont=1;
double pi=1.0, dAtual=1.0,dAnt,dCom=1.0,nume=1.0;
for(;cont<=num;cont++){
dAnt=dCom;
dAtual=dAtual+2.0;
dCom=mmc(dAtual,dAnt);
if(cont%2==0) nume=nume*(dCom/dAnt)+(dCom/dAtual);
else nume=nume*(dCom/dAnt)-(dCom/dAtual);
pi=nume/dCom;
}
pi=pi*4;
return pi;
}
double R2(int num){
int cont=1;
double pi=1.0, dAtual=1.0,dAnt,dCom=1.0,nume=1.0;
for(;cont<=num;cont++){
dAnt=dCom;
dAtual=pow((cont+1.0),2);
dCom=mmc(dAnt,dAtual);
nume=nume*(dCom/dAnt)+(dCom/dAtual);
pi=nume/dCom;
}
pi=sqrt((pi*6));
return pi;
}
int main(){
setlocale(LC_ALL,"Portuguese");
int n;
printf("Digite um numero positivo: ");
scanf("%d",&n);
printf("\nA aproximação de pi com %d termos é:\n\n",n);
printf("R1= %.15lf\n\n",R1(n));
printf("R2= %.15lf\n\n",R2(n));
system("pause");
return (0);
}
The problem is in function R2, which from the 12th term can no longer calculate and returns -1,#IND0000, I thought I could have exceeded the double limit value, and tried to change to long double, but this way only returns 0. What could be the problem?
Actually, I found out now that the mmc function returns me at some point a value like this, I switched it for a simple multiplication Dant*dAtual in R2, but at 98th term it stops working again.
– Cleber
Don’t forget to mark as resolved
– Lucas Módolo