C#编程实现取整和取余的方法
作者:清风远行 时间:2023-09-09 22:19:26
本文实例讲述了C#编程实现取整和取余的方法。分享给大家供大家参考,具体如下:
"%"为取余号,不用多说。
"/"号现在整形运算是取整,浮点运算时为除法运算,如54/10结果为5,54.0/10.0结果为5.4而且取整时不进行四舍五入只取整数部分,如54/10和56/10是5.
Math.Celling()取整数的较大数,即向上取整。相当于不管余数是什么都会进一位。如Math.Celling(54.0/10.0)结果为6.
Math.Ceiling(Convert.ToDecimal(d)).ToString() 或string res = Math.Ceiling(Convert.ToDouble(d)).ToString(); res为5 string res =
Math.Floor()取整数的较小数,即向下取整。相当于"/"号,即不管余数部分是什么都不进行进位。如Math.Floor(56.0/10.0)的结果是5.
Math.Floor(Convert.ToDecimal(d)).ToString() 或string res = Math.Floor(Convert.ToDouble(d)).ToString(); res为4
代码如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{ class Program { static void Main(string[] args)
{ Console.WriteLine("(54/10):{0}", 54 / 10);
Console.WriteLine("(56/10):{0}", 56/ 10);
Console.WriteLine("(54.0%10.0):{0}", 54.0 % 10.0);
Console.WriteLine("(56.0%10.0):{0}", 56.0 % 10.0);
Console.WriteLine("Math.Celling(54.0/10.0):{0}", Math.Ceiling(54.0 / 10.0));
Console.WriteLine("Math.Celling(56.0/10.0):{0}", Math.Ceiling(56.0 / 10.0));
Console.WriteLine("Math.Floor(54.0/10.0):{0}", Math.Floor(54.0 / 10.0));
Console.WriteLine("Math.Floor(56.0/10.0):{0}", Math.Floor(56.0 / 10.0)); } } }
C#中,关于除法"/"运算得一点问题。
现在C#与法中,"/"除后所得的值的类型,跟他的除数和被除数的类型有关。如:
int a=4;
int b=5;
float c=a/b ;
则结果为0(因为会先进行int的除法操作,得出结果0,再将结果转为float 0;);
总之,得出的数都是整形的,最终发觉原来除后所得的值的类型,跟他的除数和被除数的类型有关。所以,应写成:
float a=3;
float b=5;
float c=a/b;
这样,才能得出正确的结论!
希望本文所述对大家C#程序设计有所帮助。
标签:C#,取整,取余
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
ViewPager判断是向左划还是右划的实例
2023-12-10 04:53:18
Android微信抢红包功能的实现原理浅析
2023-11-20 19:14:40
简单理解Java的垃圾回收机制与finalize方法的作用
2023-02-04 01:49:37
![](https://img.aspxhome.com/file/2023/6/128236_0s.jpg)
MyBatis通过JDBC数据驱动生成的执行语句问题
2023-08-24 08:42:18
Java中的内部类你了解吗
2022-12-11 08:29:10
![](https://img.aspxhome.com/file/2023/0/62430_0s.png)
通过FancyView提供 Android 酷炫的开屏动画实例代码
2023-04-11 11:00:53
![](https://img.aspxhome.com/file/2023/4/139494_0s.gif)
Android自定义控件之广告条滚动效果
2022-01-27 05:57:45
![](https://img.aspxhome.com/file/2023/6/106046_0s.gif)
Java continue break制作简单聊天室程序
2022-12-20 01:23:01
Groovy动态语言使用教程简介
2022-04-28 15:05:54
java实现马踏棋盘的算法
2023-11-29 17:00:29
![](https://img.aspxhome.com/file/2023/4/60284_0s.jpg)
Android实现上拉加载更多ListView(PulmListView)
2023-11-03 19:19:44
Java中StringBuilder与StringBuffer使用及源码解读
2022-05-16 09:11:18
![](https://img.aspxhome.com/file/2023/4/97954_0s.webp)
VsCode配置java环境的详细图文教程
2022-03-29 00:56:32
![](https://img.aspxhome.com/file/2023/8/132188_0s.jpg)
java高并发的线程中断的几种方式详解
2022-08-25 01:35:09
WebView设置WebViewClient的方法
2023-09-01 05:34:58
Spring Boot 防止接口恶意刷新和暴力请求的实现
2022-05-08 03:54:58
.net 随机生成汉字
2022-01-22 08:33:33
Android实现在子线程中更新Activity中UI的方法
2022-12-16 23:57:46
java为什么会出现精度丢失这种现象你知道吗
2023-07-04 05:24:38
![](https://img.aspxhome.com/file/2023/9/104029_0s.png)
Android调用外置摄像头的方法
2021-10-19 01:25:13