AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

取整函数的实现代码

作者: 作者的头像   天气寒冷 ,  2025-07-05 22:00:25 · 河北 ,  所有人可见 ,  阅读 3


0


方法一:借助理解取整函数的意义

时间复杂度:o(n)

#include <iostream>
#include <cstring>

using namespace std;

double n;

int main()
{
    scanf("%lf", &n);

    for (int i = 0; ; i ++ )
    {
        if (n >= 0)
        {
            if (n - i < 1)
            {
                printf("%d ", i);
                break;
            }

        }
        else
        {
            double t = n * (-1) - i;
            if (t < 1 && t > 0)
            {
                printf("%d ", (-1)* i - 1);
                break;
            }
            if (t == 0)
            {
                printf("%d ", (-1)* i);
                break;
            }
        }
    }

    return 0;
}

方法二:借助函数库

时间复杂度:O(1)

#include <iostream>
#include <cstring>
#include <cmath>

using namespace std;

int main()
{
    double n;
    scanf("%lf", &n);

    int result;
    if (n >= 0) {
        result = static_cast<int>(ceil(n));  // 向上取整
    } else {
        result = static_cast<int>(floor(n)); // 向下取整
    }

    printf("%d ", result);

    return 0;
}

非负数情况(n >= 0):
ceil(n)返回大于或等于n的最小整数(例如:ceil(3.2) → 4,ceil(3.0) → 3)
static_cast[HTML_REMOVED]()将结果转换为整数类型
负数情况(n < 0):
floor(n)返回小于或等于n的最大整数(例如:floor(-3.2) → -4,floor(-3.0) → -3)
注意:直接使用floor处理负数时,其行为符合数学上的向下取整定义

https://blog.csdn.net/aouixh/article/details/53483556

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息