我在理解C中以下功能的实现时遇到问题:
#include <math.h>
#define RAD (3.14159265/180.0)
#include "fulmoon.h"
void flmoon(int n, int nph, long *jd, float *frac) {
/*This programs begin with an introductory comment summarizing their purpose and explaining
their calling sequence. This routine calculates the phases of the moon. Given an integer n and
a code nph for the phase desired (nph = 0 for new moon, 1 for first quarter, 2 for full, 3 for last
quarter), the routine returns the Julian Day Number jd, and the fractional part of a day frac
to be added to it, of the nth such phase since January, 1900. Greenwich Mean Time is assumed.*/
int i;
float am,as,c,t,t2,xtra;
c=n+nph/4.0;
t=c/1236.85;
t2=t*t;
printf("jdhdhdhd");
as=359.2242+29.105356*c;
am=306.0253+385.816918*c+0.010730*t2;
*jd=2415020+28L*n+7L*nph;
xtra=0.75933+1.53058868*c+((1.178e-4)-(1.55e-7)*t)*t2;
if (nph == 0 || nph == 2){
xtra += (0.1734-3.93e-4*t)*sin(RAD*as)-0.4068*sin(RAD*am);
}
else (nph == 1 || nph == 3){
xtra += (0.1721-4.0e-4*t)*sin(RAD*as)-0.6280*sin(RAD*am);
}
i=(int)(xtra >= 0.0 ? floor(xtra) : ceil(xtra-1.0));
*jd += i;
*frac=xtra-i;
}
我尝试了什么
我制作了一个名为fulmoon.h的头文件,如下所示:
#ifndef header_h
#define header_h
#define myName "Amrit"
void flmoon(int n, int nph, long *jd, float *frac);
#endif
然后我在主文件中调用了flmoon函数。我不明白的是参数* jd和* frac。在我尝试计算它们时,如何将它们作为输入参数?
此示例摘自第1页Numerical recipes的书。
最佳答案
参数是指针,因此在调用函数之前,您需要创建两个将保存结果的局部变量。您对函数的输入是指针,函数将在所指向的变量中产生其输出。这是允许函数返回多个值的常用方法。像这样调用函数:
long jdResult;
float fracResult;
flmoon(42, 2, &jdResult, &fracResult); // & creates a pointer to a variable
printf("Results: %l and %f\n", jdResult, fracResult);
变量名很可能是
jd
和frac
,但我选择了不同的名称只是为了避免常见的误解,即传递给函数的变量名必须与函数的参数名相同。