本文實例講述了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#程序設計有所幫助。
新聞熱點
疑難解答