整数除法相关用法:floor、ceil、round

2023-12-29 15:32:44

整数除法——舍小数,取整数
1.floor()头文件<math.h>
功能:把一个小数向下取整,即就是如果数是2.2 ,那向下取整的结果就为2.000000
原型:double floor(doube x);
x : 是需要计算的数
返回值:
? ? ? 成功:返回一个double类型的数,此数默认有6位小数
? ? ? 无失败的返回值
2.ceil()头文件
功能:把一个小数向上取整,即就是如果数是2.2 ,那向上取整的结果就为3.000000
原型:double ceil(doube x);
x : 是需要计算的数
返回值:
? ? ? ?成功:返回一个double类型的数,此数默认有6位小数
? ? ? ?无失败的返回值
头文件:#include<math.h>
3.round函数
//功能:把一个小数四舍五入,即就是如果数是2.2 ,那四舍五入的结果就为2,如果数是2.5, 那结果就是3
//原型:double round(doube x);
//x : 是需要计算的数
//头文件:#include<math.h>
除法取整的结果只保留整数部分,不进行四舍五入或其他取整方式


//——1.floor函数
floor函数计算后的结果为double类型的:
//#include<stdio.h>
//#include<math.h>
//int main()
//{
// ? ?double i = floor(2.2);
// ? ?double j = floor(-2.2);
// ? ?printf("The floor of 2.2 is %f\n", i);
// ? ?printf("The floor of 2.2 is %f\n", j);
// ? ?return 0;
//}
结果为
//The floor of 2.2 is 2.000000
//The floor of 2.2 is - 3.000000


floor函数把转换后的结果强转为int类型的(注意:floor把计算结果强转为int后,会丢失精度)
//#include<stdio.h>
//#include<math.h>
//int main()
//{
// ? ?int i = floor(2.2);
// ? ?int j = floor(2.7);
// ? ?printf("i=%d,j=%d\n", i, j);
// ? ?return 0;
//}
结果为:
//i = 2, j = 2

——2.ceil函数
ceil函数计算的结果为double类型的:
//#include<stdio.h>
//#include<stdlib.h>
//#include<math.h>
//int main()
//{
// ? ?double i = ceil(2.2);
// ? ?double j = ceil(-2.2);
// ? ?printf("The ceil of 2.2 is %f\n", i);
// ? ?printf("The ceil of 2.2 is %f\n", j);
// ? ?system("pause");
// ? ?return 0;
//}
//结果为:
//The ceil of 2.2 is 3.000000
//The ceil of 2.2 is - 2.000000


ceil函数把计算后的结果强转为int类型的:
//#include<stdio.h>
//#include<stdlib.h>
//#include<math.h>
//int main()
//{
// ? ?int i = ceil(2.2);
// ? ?int j = ceil(2.7);
// ? ?printf("i=%d,j=%d\n", i, j);
// ? ?system("pause");
// ? ?return 0;
//}
//结果为:
//i = 3, j = 3

——3.round函数
round函数的计算结果为double类型的:
//#include<stdio.h>
//#include<stdlib.h>
//#include<math.h>
//int main()
//{
// ? ?double i = round(2.2);
// ? ?double x = round(2.7);
// ? ?double j = round(-2.2);
// ? ?double y = round(-2.7);
// ? ?printf("The round of 2.2 is %f\n", i);
// ? ?printf("The round of 2.7 is %f\n", x);
// ? ?printf("The round of -2.2 is %f\n", j);
// ? ?printf("The round of -2.7 is %f\n", y);
// ? ?system("pause");
// ? ?return 0;
//}
结果为
//The round of 2.2 is 2.000000
//The round of 2.7 is 3.000000
//The round of - 2.2 is - 2.000000
//The round of - 2.7 is - 3.000000

文章来源:https://blog.csdn.net/2201_75570527/article/details/135290184
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。