我首先写了这个程序,它递归地计算pi并在误差值足够小时停止.
#include` #include #include int threads=1; double error=0.000001; double func(double); struct args{ double l; double r; double fl; double fr; double area;}; double quad(struct args*); int main(int argc, char *argv[]) { struct args* res = (struct args*)malloc(sizeof(struct args)); res->l=0; res->r=1; res->fl=1; res->fr=0; res->area=0; double ans=quad(res); free(res); ans=ans*4; printf("pi=%f\n",ans); } double func(double x){ x=(1-(x*x)); x=sqrt(x); return x; } double quad(struct args* arg){ double m=(arg->l+arg->r)/2; double fm=func(m); double larea=(arg->fl+fm)*(m-arg->l)/2; double rarea = (fm+arg->fr)*(arg->r-m)/2; struct args* arg1 = (struct args*)malloc(sizeof(struct args)); arg1->l=arg->l; arg1->r=m; arg1->fl=arg->fl; arg1->fr=fm; arg1->area=larea; struct args* arg2 = (struct args*)malloc(sizeof(struct args)); arg2->l=m; arg2->r=arg->r; arg2->fl=fm; arg2->fr=arg->fl; arg2->area=rarea; if(fabs((larea+rarea)-arg->area)>error){ if(threads<=1){ larea=quad(arg1); rarea=quad(arg2); free(arg1); free(arg2); } } return(larea+rarea); }
这个应该工作,但后来我尝试使quad
函数返回一个void pointer
而不是double
它看起来像这样.
#include` #include #include int threads=1; double error=0.000001; double func(double); struct args{ double l; double r; double fl; double fr; double area;}; void* quad(struct args*); int main(int argc, char *argv[]) { struct args* res = (struct args*)malloc(sizeof(struct args)); res->l=0; res->r=1; res->fl=1; res->fr=0; res->area=0; void* ans=quad(res); double val=*(double*)ans; val=val*4; free(res); printf("pi=%f\n",val); } double func(double x){ x=(1-(x*x)); x=sqrt(x); return x; } void* quad(struct args* arg){ double m=(arg->l+arg->r)/2; double fm=func(m); double larea=(arg->fl+fm)*(m-arg->l)/2; double rarea = (fm+arg->fr)*(arg->r-m)/2; struct args* arg1 = (struct args*)malloc(sizeof(struct args)); arg1->l=arg->l; arg1->r=m; arg1->fl=arg->fl; arg1->fr=fm; arg1->area=larea; struct args* arg2 = (struct args*)malloc(sizeof(struct args)); arg2->l=m; arg2->r=arg->r; arg2->fl=fm; arg2->fr=arg->fl; arg2->area=rarea; if(fabs((larea+rarea)-arg->area)>error){ if(threads<=1){ void* p1=quad(arg1); void* p2=quad(arg2); larea=*((double*)p1); rarea=*((double*)p2); free(arg1); free(arg2); } } double ret= (larea+rarea); void*poin=&ret; return poin; }
这个程序在编译时只给我一个完全不同的结果,0.042298而不是3.14159.我对C很新,并且使用指针,所以我确定我对转换搞砸了但是我不能为我的生活弄清楚在哪里.
任何帮助弄清楚为什么这两个程序产生不同的结果将不胜感激.谢谢.
你正在返回指针ret
.一个本地变量quad()
.当你看它时,它已被替换.
解除引用无效指针也是未定义的行为.这意味着您的编译器可以随意执行任何操作,例如格式化硬盘或启动WW3.