C语言 ceil函数在C中的实现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2796639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:24:18  来源:igfitidea点击:

Implementation of ceil function in C

cceil

提问by AGeek

I have two questions regarding ceil()function..

我有两个关于ceil()函数的问题..

  1. The ceil()function is implemented in C. If I use ceil(3/2), it works fine. But when I use ceil(count/2), if value of count is 3, then it gives compile time error.

    /tmp/ccA4Yj7p.o(.text+0x364): In function FrontBackSplit': : undefined reference toceil' collect2: ld returned 1 exit status

    How to use the ceil function in second case? Please suggest.

  2. How can I implement my own ceil function in C. Please give some basic guidelines.

  1. ceil()函数是用 C 实现的。如果我使用ceil(3/2),它工作正常。但是当我使用时ceil(count/2),如果 count 的值为 3,那么它会给出编译时错误。

    /tmp/ccA4Yj7p.o(.text+0x364): 在函数FrontBackSplit': : undefined reference toceil' collect2: ld 返回 1 退出状态

    如何在第二种情况下使用 ceil 函数?请建议。

  2. 我如何在 C 中实现我自己的 ceil 函数。请给出一些基本指南。

Thanks.

谢谢。

采纳答案by Adam Rosenfield

The ceil()function is implemented in the math library, libm.so. By default, the linker does not link against this library when invoked via the gcc frontend. To link against that library, pass -lmon the command line to gcc:

ceil()函数在数学库中实现,libm.so. 默认情况下,当通过 gcc 前端调用时,链接器不会链接到这个库。要链接到该库,-lm请将命令行传递给 gcc:

gcc main.c -lm

回答by nintendo

Try this out:

试试这个:

#define CEILING_POS(X) ((X-(int)(X)) > 0 ? (int)(X+1) : (int)(X))
#define CEILING_NEG(X) ((X-(int)(X)) < 0 ? (int)(X-1) : (int)(X))
#define CEILING(X) ( ((X) > 0) ? CEILING_POS(X) : CEILING_NEG(X) )

Check out the link for comments, proof and discussion: http://www.linuxquestions.org/questions/programming-9/ceiling-function-c-programming-637404/

查看评论、证明和讨论的链接:http: //www.linuxquestions.org/questions/programming-9/ceiling-function-c-programming-637404/

回答by Michael Aaron Safyan

The prototype of the ceilfunction is:

ceil函数的原型是:

double ceil(double)

My guess is that the type of your variable countis not of type double. To use ceil in C, you would write:

我的猜测是您的变量count类型不是 double 类型。要在 C 中使用 ceil,你可以这样写:

#include <math.h>
// ...
double count = 3.0;
double result = ceil(count/2.0);

In C++, you can use std::ceilfrom <cmath>; std::ceil is overloaded to support multiple types:

在 C++ 中,您可以使用std::ceilfrom <cmath>; std::ceil 被重载以支持多种类型:

#include <cmath>
// ...
double count = 3.0;
double result = std::ceil(count/2.0);

回答by Anonymous

double ceil (double x) {
    if (x > LONG_MAX) return x; // big floats are all ints
    return ((long)(x+(0.99999999999999997)));
}