编写自己的数学下位函数C的实现 [英] Write your own implementation of math's floor function, C

查看:104
本文介绍了编写自己的数学下位函数C的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑math.h中可用的floor功能.它很容易使用:

I was thinking about the floor function available in math.h. It is very easy to use it:

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

int main(void)
{
  for (double a = 12.5; a < 13.4; a += 0.1)
    printf("floor of  %.1lf is  %.1lf\n", a, floor(a));
  return 0;
}

如果我想编写自己的实现该怎么办?看起来像这样吗?

What if I would like to write my own implementation of it? Would it look simply like this:

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

double my_floor(double num)
{
    return (int)num;
}

int main(void)
{
    double a;

    for (a = 12.5; a < 13.4; a += 0.1)
        printf("floor of  %.1lf is  %.1lf\n", a, floor(a));

    printf("\n\n");

    for (a = 12.5; a < 13.4; a += 0.1)
        printf("floor of  %.1lf is  %.1lf\n", a, my_floor(a));

    return 0;
}

?

似乎对负数(my_floor)无效,但第二个似乎没问题(my_floor_2):

It seems it does not work with negative numbers (my_floor), but the second one seems to be fine (my_floor_2):

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

double my_floor(double num)
{
    return (int)num;
}

double my_floor_2(double num)
{
    if(num < 0)
        return (int)num - 1;
    else
        return (int)num;
}

int main(void)
{
    double a1 = -12.5;

    printf("%lf\n", floor(a1));
    printf("%lf\n", my_floor(a1));
    printf("%lf\n", my_floor_2(a1));

    return 0;
}

程序输出:

其中之一最终是否正确?

Is one of them eventually correct or not?

推荐答案

否,您不能以这种方式解决.编写自己的实现的最好方法是从平台上的C标准库中窃取实现.但是请注意,这可能包含特定于平台的细微差别,因此可能无法移植.

No you can't tackle it this way. The best way of writing your own implementation is to steal the one from the C Standard Library on your platform. But note that might contain platform specific nuances so might not be portable.

C标准库floor函数通常很聪明,因为它无法通过转换为整数类型来工作.如果这样做,您将冒signed整数溢出的风险,其行为是不确定的. (请注意,int的最小范围是-32767到+32767).

The C Standard Library floor function is typically clever in that it doesn't work by taking a conversion to an integral type. If it did then you'd run the risk of signed integer overflow, the behaviour of which is undefined. (Note that the smallest possible range for an int is -32767 to +32767).

精确的实现还取决于平台上使用的浮点方案.

The precise implementation is also dependent on the floating point scheme used on your platform.

对于使用IEEE754浮点的平台,并且类型您可以 采用以下方案:

For a platform using IEEE754 floating point, and a long long type you could adopt this scheme:

  1. 如果数字的大小大于2的53次幂,则将其返回(因为它已经是整数).
  2. 否则,强制转换为64位类型(长长),然后将其返回.

这篇关于编写自己的数学下位函数C的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆