c++向下取整
时间: 2023-07-01 16:26:23 浏览: 202
在 C++ 中向下取整可以使用下面两种方法:
1. 使用 floor 函数:floor 函数属于 math.h 头文件,可以对浮点数进行向下取整操作。
```c++
#include <iostream>
#include <cmath>
int main() {
double num = 3.7;
std::cout << floor(num) << std::endl; // 输出 3
return 0;
}
```
2. 强制类型转换:将浮点数强制转换成整型,由于整型只保留整数部分,因此会自动进行向下取整操作。
```c++
#include <iostream>
int main() {
double num = 3.7;
std::cout << (int)num << std::endl; // 输出 3
return 0;
}
```
相关问题
C++向下取整和向上取整。
C语言中,向下取整可以使用floor函数,向上取整可以使用ceil函数。
floor函数的头文件为<math.h>,其用法如下:
```c
double floor(double x);
```
其中,x为需要进行向下取整的值,函数返回值为不大于x的最大整数。
例如:
```c
#include <stdio.h>
#include <math.h>
int main()
{
double x = 3.8;
double y = -2.5;
printf("floor(%.1f) = %.1f\n", x, floor(x));
printf("floor(%.1f) = %.1f\n", y, floor(y));
return 0;
}
```
输出结果为:
```
floor(3.8) = 3.0
floor(-2.5) = -3.0
```
ceil函数的头文件同样为<math.h>,其用法如下:
```c
double ceil(double x);
```
其中,x为需要进行向上取整的值,函数返回值为不小于x的最小整数。
例如:
```c
#include <stdio.h>
#include <math.h>
int main()
{
double x = 3.8;
double y = -2.5;
printf("ceil(%.1f) = %.1f\n", x, ceil(x));
printf("ceil(%.1f) = %.1f\n", y, ceil(y));
return 0;
}
```
输出结果为:
```
ceil(3.8) = 4.0
ceil(-2.5) = -2.0
```
C++向下取整函数floor函数用法实例
floor函数是C语言中的一个数学函数,用于向下取整,即返回不大于输入参数的最大整数值。其用法如下:
```c
#include <math.h>
double floor(double x);
float floorf(float x);
long double floorl(long double x);
```
其中,x为要进行向下取整的数值,函数返回值为double、float或long double类型的向下取整结果。
例如,将3.8向下取整,结果为3:
```c
#include <stdio.h>
#include <math.h>
int main()
{
double x = 3.8;
double result = floor(x);
printf("floor(%.1f) = %.1f\n", x, result);
return 0;
}
```
输出结果为:
```
floor(3.8) = 3.0
```
注意,当x为负数时,floor函数返回的是不大于x的最大整数,即向下取整的结果为负数。例如,将-3.8向下取整,结果为-4:
```c
#include <stdio.h>
#include <math.h>
int main()
{
double x = -3.8;
double result = floor(x);
printf("floor(%.1f) = %.1f\n", x, result);
return 0;
}
```
输出结果为:
```
floor(-3.8) = -4.0
```