C#编程实现取整和取余的方法_C#教程-查字典教程网
C#编程实现取整和取余的方法
C#编程实现取整和取余的方法
发布时间:2016-12-28 来源:查字典编辑
摘要:本文实例讲述了C#编程实现取整和取余的方法。分享给大家供大家参考,具体如下:"%"为取余号,不用多说。"/"号现在整形运算是取整,浮点运算时...

本文实例讲述了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#教程学习
    热门C#教程学习
    编程开发子分类