这是我当前的代码,输出如下:
请输入大于 2299160 的儒略日数字
2299161
15 10 1582
但是,如果有小数点 2299161.1 等,这不会为我提供准确的时间。
这将如何用 C 实现?我已经知道数学了:
0.1 days = 0.1 * 24 hours = 2 hours (remainder 0.4 hours),
0.4 * 60 minutes = 24 minutes (remainder 0.0 seconds)
0.0 * 60 seconds = 0 seconds
<小时/>
#include <stdio.h>
int main( ) {
double jdn; /* you will need to store the user's input here... */
long lc, kc, nc, ic, jc;
int day, month, year;
printf("Please Enter a Julian Day number greater than 2299160 \n");
scanf("%lf",&jdn);
if( jdn > 2299160 ){
printf("%d\n",jdn);
lc = jdn + 68569;
nc = ((4 * lc) / 146097);
lc = lc - ((146097 * nc + 3) / 4);
ic = ((4000 * (lc + 1)) / 1461001);
lc = lc - ((1461 * ic) / 4) + 31;
jc = ((80 * lc) / 2447);
day = lc - ((2447 * jc) / 80);
lc = (jc / 11);
month = jc + 2 - 12 * lc;
year = 100 * (nc - 49) + ic + lc;
printf("%d %d %d\n", day, month, year);
}
else {
printf("Invalid number");
}
return 0;
}
最佳答案
推荐@Paul R使用的floor()
、@user3386109使用的整数%
和*
的组合,并使用round()
.
#include <math.h>
double frac_d = jdn - floor(jdn); // @Paul R
#define SecPerDay (24L*60*60)
long frac_l = (long) round(frac_d * SecPerDay);
int sec = frac_l % 60; // @user3386109
frac_l /= 60;
int min = frac_l % 60;
frac_l /= 60;
int hrs = total;
如果出现负儒略日期时间,则使用 floor()
与 modf()
非常重要。
在分配给整数之前对 double 值进行舍入可确保像 12.99999999 这样的值采用整数值 13 而不是 12。
出于可移植性的原因,对于可能超过 32767 的值,优先选择 long
而不是 int
。
[编辑]
我对以下说法的担忧并未得到证实。任何一种计算 h,m,s
的方法都可以得到一致的值。仍然更喜欢整数方法,因为代码更少并且更容易控制舍入。
“从一个整数计算 h、m、s 可确保分数的值一致。” (无效)
关于C:将儒略日期转换为公历日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26165859/