无法在c中获得相同的答案,并且具有相同的功能

问题描述 投票:-2回答:1

我使用c来计算以下函数,但无法得到正确的答案(在excel中使用函数“INT”它是正确答案,在c中,我使用“floor”替换。)。

功能:

enter image description here

我在c中的代码:

int ans;
ans = 1721013.5+367*Y-floor((7/4)*(Y+floor((M+9)/12)))+
        D+h/24+floor(275*M/9);

当Y = 2018,M = 3,D = 9,h = 9时,我得到错误答案2459700

正确答案:2458187

c excel
1个回答
1
投票

用double替换所有常量int就足够了:

#include <stdio.h>
#include <math.h>

int main()
{
  int Y=2018,M=3,D=9,h=9; /* can be double of course */
  int ans = ceil(1721013.5+367.0*Y-floor((7.0/4.0)*(Y+floor((M+9.0)/12.0)))+
    D+h/24.0+floor(275.0*M/9.0));

  printf("%d\n", ans);
}

我需要使用ceil打印2458187否则我得到2458186

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra f.c -lm
pi@raspberrypi:/tmp $ ./a.out
2458187

在初始问题之外的附加注释,因为表达式可以通过常量(没有变量)来减少,计算可以在编译时而不是在执行时完成:

pi@raspberrypi:/tmp $ gcc -O3 f.c
pi@raspberrypi:/tmp $ cat f.s 
    .arch armv6
    ...
main:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 0, uses_anonymous_args = 0
    push    {r4, lr}
    ldr r1, .L3
    ldr r0, .L3+4
    bl  printf
    mov r0, #0
    pop {r4, pc}
.L4:
    .align  2
.L3:
    .word   2458187
    ...

这里的值是在编译时计算的:.word 2458187

© www.soinside.com 2019 - 2024. All rights reserved.