h-b-z-d-j-s-m 发表于 2022-5-20 08:36:28

精确度问题

题目是根据公式求Π,要求精确度为0.0005,即某项小于0.0005时停止
为什么我的运行出来结果跟答案给的结果不一样,哪里错了?
fun函数里面为自己写的
答案写的是double s=0.0,s1=1.0;
int n=1;
while(s1>=eps)
{
s=s+s1;
s1=s1*n/(2*n+1);
n++;
}
return 2*s;

fun函数里面是我自己写的,麻烦帮我看下
#include <stdio.h>
#include <math.h>
doublefun ( doubleeps)
{
      double pi,a=1.0,b=1.0,i=1.0,t;
      pi=1.0;
      t=1.0;
      while(t>=eps)
      {
                a*=i;
                b*=(2*i+1);
                t=a/b;
                pi+=t;
                i++;
      }
      return (2*pi);


}

void main( )
{ doublex;void NONO ();
printf("Input eps:") ;
scanf("%lf",&x); printf("\neps = %lf, PI=%lf\n", x, fun(x));
NONO();
}

void NONO ()
{/* 本函数用于打开文件,输入数据,调用函数,输出数据,关闭文件。 */
FILE *fp, *wf ;
int i ;
double x ;

fp = fopen("in.dat","r") ;
wf = fopen("out.dat","w") ;
for(i = 0 ; i < 10 ; i++) {
    fscanf(fp, "%lf", &x) ;
    fprintf(wf, "%lf\n", fun(x)) ;
}
fclose(fp) ;
fclose(wf) ;
}

人造人 发表于 2022-5-20 08:45:10

?
https://fishc.com.cn/forum.php?mod=redirect&goto=findpost&ptid=213582&pid=5842010

h-b-z-d-j-s-m 发表于 2022-5-20 10:42:44

人造人 发表于 2022-5-20 08:45
?
https://fishc.com.cn/forum.php?mod=redirect&goto=findpost&ptid=213582&pid=5842010

那个没有解决我的问题,我想看看我的方法哪里错了

人造人 发表于 2022-5-20 12:36:14

h-b-z-d-j-s-m 发表于 2022-5-20 10:42
那个没有解决我的问题,我想看看我的方法哪里错了

???
https://fishc.com.cn/forum.php?mod=redirect&goto=findpost&ptid=213582&pid=5842010

#include <stdio.h>
#include <math.h>

double fun(double eps) {
    double pi, a = 1.0, b = 1.0, i = 1.0, t;
    pi = 1.0;
    t = 1.0;
    //while(t >= eps) {
    while(1) {
      a *= i;
      b *= (2 * i + 1);
      t = a / b;
      if(t < eps) break;
      pi += t;
      i++;
    }
    return (2 * pi);
}

// void main( )
int main(void) {
    double x;
    void NONO();
    //printf("Input eps:");
    //scanf("%lf", &x);
    x = 0.0005;
    printf("\neps = %lf, PI=%lf\n", x, fun(x));
    //NONO();
}

void NONO() { /* 本函数用于打开文件,输入数据,调用函数,输出数据,关闭文件。 */
    FILE *fp, *wf;
    int i;
    double x;

    fp = fopen("in.dat", "r");
    wf = fopen("out.dat", "w");
    for(i = 0; i < 10; i++) {
      fscanf(fp, "%lf", &x);
      fprintf(wf, "%lf\n", fun(x));
    }
    fclose(fp);
    fclose(wf);
}
页: [1]
查看完整版本: 精确度问题