【发布时间】:2015-11-21 04:39:05
【问题描述】:
我被分配了以下问题:
制作一个 Fortran 程序,该程序将能够读取学位 [0-360] 检查有效范围(不是类型),它将能够从以下等式计算和打印 cos(x),其中 x 是以弧度为单位:
cos(x)=1-x^2/2! + x^4/4!-x^6/6!+x^8/8!-...
作为收敛标准假设10^(-5) 使用两次连续重复之间的绝对误差(我想这意味着做)。
对于! 的计算,应该使用最大可能的整数类型。最后应该在屏幕上打印重复的总数。
所以我的代码是这样的:
program ex6_pr2
implicit none
!Variables and Constants
integer::i
real*8::fact,fact2 !fact=factorial
real,parameter::pi=3.14159265
double precision::degree,radiants,cosradiants,s,oldcosradiants,difference !degree,radiants=angle
print*,'This program reads and calculates an angle`s co-sinus'
print*,'Please input the degrees of the angle'
read*,degree
do while(degree<0 .or. degree>360) !number range
read*,degree
print*,'Error input degree'
cycle
end do
radiants=(degree*pi/180)
fact=1
fact2=1
s=0
cosradiants=0
!repeat structure
do i=2,200,1
fact=fact*i
fact2=fact2*(i+2)
oldcosradiants=cosradiants
cosradiants=(-(radiants)**i/fact)+(((radiants)**(i+2))/fact2)
difference=cosradiants-oldcosradiants
s=s+cosradiants
if(abs(difference)<1e-5) exit
end do
!Printing results
print*,s+1.
end program
对于 45 度(或 pi/4)等角度,我得到正确的结果,而对于 90 度或 180 等其他角度,我得到错误的结果。
我检查了我认为隐藏错误的阶乘(至少对我而言)。
由于以下错误,我创建了另一个似乎无法运行的代码:FUNCTION 名称,(PROJECT2_EX6~FACT 的结果),在未预期的地方使用,可能缺少“()”
program project2_ex6
implicit none
integer(kind=3)::degrees,i,sign
integer::n
double precision::x,err_limit,s_old,s
real,parameter::pi=3.14159265359
print*,'This program calculates the cos(x)'
print*,"Enter the angle's degrees"
read*,degrees
do
if(degrees<0.or.degrees>360) then
print*,'Degrees must be between 0-360'
else
x=pi*degrees/180
exit
end if
end do
sign=1
sign=sign*(-1)
err_limit=1e-5
n=0
s=0
s_old=0
do
do i=1,n
end do
s=(((-1.)**n/(fact(2.*n)))*x**(2.*n))*sign
s=s+s_old
n=n+1
if(abs(s-s_old)<1e-5) then
exit
else
s_old=s
cycle
end if
end do
print*,s,i,n
contains
real function fact(i)
double precision::fact
integer::i
if(i>=1) then
fact=i*fact(i-1)
else
fact=1
end if
return
end function
end program
【问题讨论】:
-
以什么方式“错误”?
123当你期望1错了?或者10^-9当你期望0错了?请做一些诊断。 -
如果你
writefact1我想你会看到2,6,24..正确的阶乘,但只有奇数会出现在你的计算中(对吗?)。fact2去3,15..根本不是阶乘。要点开始缓慢并使用大量调试写入语句来确保事情按照您的想法进行。 -
请不要使用
integer(kind=3),这是非常糟糕的主意。你的程序变得无法被许多编译器编译。无论如何,这是一个新问题,你应该把它放在一个新问题中。
标签: fortran trigonometry