我创建了几个不同语言的程序来使用梯形和(C, Perl, and Python similar loops different results)来计算pi,现在我想在Fortran中编写一个。我对这门语言一无所知,我写了这篇文章:
program cpi
double precision n, val, pi
integer i, num
n = 1000
num = 1000
val = 0
do i = 1, num
val = val + ((1 - (i ** 2)) ** 0.5)
end do
pi = (2 / n)*(1 + (2 * val))
print *, pi
end program cpi
当我使用NaN
编译它时返回gfortran
并运行它。这意味着什么?如何更改它以使其工作?我要比较的C程序是:
#include <stdio.h>
#include <math.h>
double n = 1000, a, h = 0, t, val, pi;
int main(void)
{
for(a = 1; a < n; ++a) {
t = a/n;
val = pow(1.0-(t*t), 0.5);
h+=val;
}
h = h*2.0;
pi = (2.0/n)*(1.0+h);
printf("%.20f\n", pi);
return 0;
}
有关修复Fortran程序的任何输入都会非常好。
答案 0 :(得分:1)
感谢@chux,该程序现在正在运行:
program cpi
double precision n, val, pi
integer i, num
n = 1000
num = 1000
val = 0
do i = 1, num
val = val + ((1 - ((i / n) ** 2)) ** 0.5)
end do
pi = (2 / n)*(1 + (2 * val))
print *, pi
end program cpi