深度理解取余取模运算

本文深入探讨了C语言中的取余运算,包括向零取整、向负无穷取整和向正无穷取整的概念,并通过具体例子进行阐述,总结了浮点数和整数除法的各种取整方式。
摘要由CSDN通过智能技术生成

深度理解取余运算

向零取整

首先打印一段代码

#include <stdio.h>

int main()
{
    int i = -2.9;
    int j = 2.9;
    pritnf("%d\n, i");// -2
    pritnf("%d\n, j");// 2
    return 0;
}

打印出来发现,i的结果是-2,j的结果是2,有一个trunc函数和这个例子同作用

image-20210822110827388

向负无穷取整
#include <stdio.h>
#include <math.h>

int main()
{
    printf("%.1f\n", floor(-2.9)); //-3
	printf("%.1f\n", floor(-2.1)); //-3
	printf("%.1f\n", floor(2.9)); //2
	printf("%.1f\n", floor(2.1)); //2
    return 0;
}

本质是向负无穷取整

image-20210822111301228

向正无穷取整
#include <stdio.h>
#include <math.h>

int main()
{
    printf("%.1f\n", ceil(-2.9)); //-2
	printf("%.1f\n", ceil(-2.1)); //-2
	printf("%.1f\n", ceil(2.9)); //3
	printf("%.1f\n", ceil(2.1)); //3
    return 0;
}

本质是向正无穷取整

image-20210822111457905

#include <stdio.h>
#include <math.h>

int main()
{
    printf("%.1f\n", round(2.1));
	printf("%.1f\n", round(2.9));
	printf("%.1f\n", round(-2.1));
	printf("%.1f\n", round(-2.9));
    return 0;
}

本质是四舍五入

汇总例子
#include <stdio.h>
#include <math.h>

int main()
{
const char * format = "%.1f \t%.1f \t%.1f \t%.1f \t%.1f\n";
printf("value\tround\tfloor\tceil\ttrunc\n");
printf("-----\t-----\t-----\t----\t-----\n");
printf(format, 2.3, round(2.3), floor(2.3), ceil(2.3), trunc(2.3));
printf(format, 3.8, round(3.8), floor(3.8), ceil(3.8), trunc(3.8));
printf(format, 5.5, round(5.5), floor(5.5), ceil(5.5), trunc(5.5));
printf(format, -2.3, round(-2.3), floor(-2.3), ceil(-2.3), trunc(-2.3));
printf(format, -3.8, round(-3.8), floor(-3.8), ceil(-3.8), trunc(-3.8));
return 0;
}

image-20210822114420946

结论:浮点数(整数/整数),是有很多取整方式的。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值