C语言符号 | 您所在的位置:网站首页 › c语言如何取模 › C语言符号 |
目录 前言 取整 向0取整 向-∞取整 向+∞取整 四舍五入取整 汇总 取模\余 对于正数取模 对于负数取模 取余和取模的理解 前言本文主要讲解并真正理解取余\取模运算是怎样的! 取整首先取整有四种类型: 向0取整向-∞取整向+∞取整四舍五入取整 向0取整 示例: int main() { //本质是向0取整 int i = -2.9; int j = 2.9; printf("%d\n", i); //结果是:-2 printf("%d\n", j); //结果是:2 return 0; }注:运行结果并不是像我们想的四舍五入数学取整,在C语言中本质是向0取整 这里我们需要ceil库函数(同样是math.h头文件) 示例: #include #include int main() { //本质是向+∞取整,注意输出格式 printf("%.1f\n", ceil(-2.1)); //-2 printf("%.1f\n", ceil(2.9)); //3 printf("%.1f\n", ceil(2.1)); //3 return 0; }这里我们需要round库函数(math.h头文件) 示例: #include #include 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 #include 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)); printf(format, -5.5, round(-5.5), floor(-5.5), ceil(-5.5), trunc(-5.5)); return 0; } 输出结果:结论:浮点数(整数/整数),是有很多的取整方式的 取模\余 定义: 如果a和d是两个自然数,d非零,可以证明存在两个唯一的整数 q 和 r 满足 a = q*d + r 且0 ≤ r < d。其中,q 被称为商,r 被称为余数 对于正数取模 示例: int main() { int a = 10; int d = 3; printf("%d\n", a%d); //结果是1 (c,python结果相同) //因为:a=10,d=3,q=3,r=1 0 |
CopyRight 2018-2019 实验室设备网 版权所有 |