天线功能:我们如何实现自己? [英] Ceil function: how can we implement it ourselves?

查看:171
本文介绍了天线功能:我们如何实现自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道C ++为我们提供了ceil函数。对于实践,我想知道我们如何在C ++中实现ceil函数。方法的签名是
public static int ceil(float num)

I know that C++ provides us with a ceil function. For practice, I was wondering how can we implement the ceil function in C++. The signature of the method is public static int ceil(float num)

请提供一些洞察。

我想到一个简单的方法:将num转换为字符串,找到小数点的索引,检查小数部分是否大于0.如果是,则返回num + 1 else return num。但我想避免使用字符串转换

I thought of a simple way: Convert num to a string, find the index of the decimal point, check if the decimal part is greater than 0. If yes, return num+1 else return num. But I want to avoid using the string conversion

推荐答案

这里是一个天真的实现正数(这使用的事实, (int)截断到零):

Here is a naive implementation for positive numbers (this uses the fact that casting to (int) truncates toward zero):

int ceil(float num) {
    int inum = (int)num;
    if (num == (float)inum) {
        return inum;
    }
    return inum + 1;
}

很容易将它扩展为使用负数。

It is easy to extend this to work with negative numbers too.

您的问题是要求返回 int 的函数,但通常 ceil()函数返回与其参数相同的类型,所以没有问题的范围(即 float ceil(float num))。例如,如果 num 为1e20,则上述函数将失败。

Your question asked for a function returning int, but normally the ceil() function returns the same type as its argument so there are no problems with the range (that is, float ceil(float num)). For example, the above function will fail if num is 1e20.

这篇关于天线功能:我们如何实现自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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