首页 > 编程 > C# > 正文

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

2019-10-29 21:36:23
字体:
来源:转载
供稿:网友

这篇文章主要介绍了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; 
  2. using System.Collections.Generic; 
  3. using System.Text; 
  4. namespace ConsoleApplication5 
  5. class Program { static void Main(string[] args) 
  6. { Console.WriteLine("(54/10):{0}", 54 / 10); 
  7. Console.WriteLine("(56/10):{0}", 56/ 10); 
  8. Console.WriteLine("(54.0%10.0):{0}", 54.0 % 10.0); 
  9. Console.WriteLine("(56.0%10.0):{0}", 56.0 % 10.0); 
  10. Console.WriteLine("Math.Celling(54.0/10.0):{0}", Math.Ceiling(54.0 / 10.0)); 
  11. Console.WriteLine("Math.Celling(56.0/10.0):{0}", Math.Ceiling(56.0 / 10.0)); 
  12. Console.WriteLine("Math.Floor(54.0/10.0):{0}", Math.Floor(54.0 / 10.0)); 
  13. Console.WriteLine("Math.Floor(56.0/10.0):{0}", Math.Floor(56.0 / 10.0)); } } } 

C#中,关于除法"/"运算得一点问题。

现在C#与法中,"/"除后所得的值的类型,跟他的除数和被除数的类型有关。如:

 

 
  1. int a=4; 
  2. int b=5; 
  3. float c=a/b ; 

则结果为0(因为会先进行int的除法操作,得出结果0,再将结果转为float 0;);

总之,得出的数都是整形的,最终发觉原来除后所得的值的类型,跟他的除数和被除数的类型有关。所以,应写成:

 

 
  1. float a=3; 
  2. float b=5; 
  3. float c=a/b; 

这样,才能得出正确的结论!

希望本文所述对大家C#程序设计有所帮助。


注:相关教程知识阅读请移步到c#教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表