C#编程实现取整和取余的方法

2019-12-30 11:10:52丽君

易采站长站为您分析C#编程实现取整和取余的方法,结合实例形式分析了C#中Math.Celling与Math.Floor函数的相关使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了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

代码如下:

 

 
  1. using System;  using System.Collections.Generic; 
  2. using System.Text;  namespace ConsoleApplication5 
  3. { class Program { static void Main(string[] args)  { Console.WriteLine("(54/10):{0}", 54 / 10); 
  4. Console.WriteLine("(56/10):{0}", 56/ 10);  Console.WriteLine("(54.0%10.0):{0}", 54.0 % 10.0); 
  5. 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)); 
  6. 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)); 
  7. Console.WriteLine("Math.Floor(56.0/10.0):{0}", Math.Floor(56.0 / 10.0)); } } }