[刷题] PTA 7-50 近似求PI

PTA

7-50 近似求PI

网友代码:

 1 include <stdio.h>
 2 
 3 int main(){
 4     double eps, sum=1, i, temp=1;
 5     scanf("%le", &eps);
 6     for(i=1; temp>eps; i++){
 7         temp = temp*i/(2*i+1);
 8         sum += temp;
 9     }
10     printf("PI = %.5f\n", 2*sum);
11 
12     return 0;
13 }

我的代码:

 1 include<stdio.h>
 2 int main() {
 3     int fz=1,fm=1,k=1;
 4     double t=1.0,pi=1.0,eps;
 5     scanf("%le",&eps);
 6     while(t>=eps) {
 7         fz*=k;
 8         fm*=(2*k+1);
 9         t = (double)fz/fm;
10         pi += t;
11         k++;
12     }
13     printf("%lf",2*pi);
14 }

数据大了会报错,k会超出int范围

几点不足:

1、变量类型不一致容易出错

2、变量太多程序不易读

 

posted @ 2019-04-24 22:18  cxc1357  阅读(745)  评论(0编辑  收藏  举报