C\C++ 向上、向下取整函数 floor() ceil()

本文详细介绍了C++中floor和ceil两个数学函数的使用方法,通过实例演示了如何向下和向上取整,适用于初学者和需要复习C++基础的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

floor(x)向下取整,返回一个<=x的int整型。

ceil(x)向上取整,返回一个>=x的int整型。

#include<bits/stdc++.h>
using namespace std;
int main(){
	cout << floor(4.111)<<endl;
	cout << floor(4.9)<<endl;
	cout << ceil(4.111) << endl;
	cout << ceil(4.9) << endl;
	return 0;
}

 

### 浮点数向上向下取整函数 #### C++ 中的实现及用法 C++ 提供了 `ceil()` 和 `floor()` 函数来处理浮点数的向上向下取整。这些函数位于 `<cmath>` 头文件中。 - **向上取整**: 使用 `std::ceil(x)` 可以得到不小于给定浮点数 `x` 的最小整数值[^1]。 ```cpp #include <iostream> #include <cmath> int main() { double num = 3.14; std::cout << "Ceil of " << num << ": " << std::ceil(num) << std::endl; // 输出 Ceil of 3.14: 4 return 0; } ``` - **向下取整**: 使用 `std::floor(x)` 能够获得不大于给定浮点数 `x` 的最大整数值。 ```cpp #include <iostream> #include <cmath> int main() { double num = 3.87; std::cout << "Floor of " << num << ": " << std::floor(num) << std::endl; // 输出 Floor of 3.87: 3 return 0; } ``` #### Python 中的实现及用法 Python 内置模块 `math` 提供了类似的函数用于浮点数的操作: - **向上取整**: 利用 `math.ceil(x)` 方法可以获取大于等于指定实参 `x` 的最接近整数[^2]。 ```python import math num = 3.14 print(f"Ceil of {num}: {math.ceil(num)}") # 输出 Ceil of 3.14: 4 ``` - **向下取整**: 应用 `math.floor(x)` 来取得一个小于或等于参数 `x` 并且是最靠近它的整数。 ```python import math num = 3.87 print(f"Floor of {num}: {math.floor(num)}") # 输出 Floor of 3.87: 3 ``` #### Java 中的实现及用法 Java 的 `Math` 类同样包含了这两个功能的方法: - **向上取整**: `Math.ceil(double a)` 返回的是一个双精度类型的值,它是大于或等于参数 `a` 的最小(即最近)整数值。 ```java public class Main { public static void main(String[] args) { double num = 3.14; System.out.println("Ceil of " + num + ": " + Math.ceil(num)); // 输出 Ceil of 3.14: 4.0 } } ``` - **向下取整**: `Math.floor(double a)` 将返回不超过参数 `a` 的最大(即最近)整数值作为双精度类型的结果。 ```java public class Main { public static void main(String[] args) { double num = 3.87; System.out.println("Floor of " + num + ": " + Math.floor(num)); // 输出 Floor of 3.87: 3.0 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值