当前位置: 移动技术网 > IT编程>开发语言>c# > C#编程实现取整和取余的方法

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网