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

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

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

头文件是<cmath>或<math.h>

<pre name="code" class="cpp">#include "stdafx.h"
#include<iostream>
#include<cmath>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	cout << floor(4)<<endl;
	cout << floor(4.9)<<endl;
	cout << ceil(4.111) << endl;
	cout << ceil(4.9) << endl;
	system("pause");
	return 0;
}

 运行结果: 

 

### C++ 中实现 `floor` 和 `ceil` 函数C++ 编程语言中,可以利用标准库中的 `<cmath>` 头文件来调用 `floor()` 和 `ceil()` 函数。这两个函数分别用于执行向下取整和向上取整操作。 #### 向下取整 (`floor`) 的例子 当应用 `floor()` 函数于数值时,该函数会返回不大于给定浮点数的最大整数值。对于正数而言,这意味着去掉小数部分;而对于负数来说,则是向更远离零的方向舍入到下一个较低的整数[^2]。 ```cpp #include <iostream> #include <cmath> // 导入 cmath 库以便使用 floor() using namespace std; int main() { double num1 = 2.8; double result_floor_positive = floor(num1); cout << "Floor value of " << num1 << ": " << result_floor_positive << endl; double num2 = -2.8; double result_floor_negative = floor(num2); cout << "Floor value of " << num2 << ": " << result_floor_negative << endl; return 0; } ``` 这段代码展示了如何计算两个不同符号实数(正值与负值)通过 `floor()` 方法得到的结果。 #### 向上取整 (`ceil`) 的例子 另一方面,`ceil()` 函数的作用是从指定的小数往上找到最接近它的最小整数。换句话说,它总是朝着更大的方向四舍五入至最近的一个整数,无论这个数字是不是已经是一个完整的整数[^3]。 ```cpp #include <iostream> #include <cmath> using namespace std; int main(){ float input_value; cout << "Enter a floating point number: "; cin >> input_value; float ceiling_result = ceil(input_value); cout << "Ceiling value of " << input_value << " is " << ceiling_result << endl; return 0; } ``` 此程序让用户输入一个小数并显示其对应的天花板值即向上取整后的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值