C#中:我怎样做简单的算术,舍入,对整数? [英] C#: How do I do simple math, with rounding, on integers?
本文介绍了C#中:我怎样做简单的算术,舍入,对整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想的等式的结果舍入到最接近的整数。
例如
137 *(3/4)= 103
考虑下面的不正确的代码。
INT宽度1 = 4;
INT height1 = 3;
INT宽2 = 137;
INT身高2 =宽2 *(height1 /宽度1);
什么是用C#进行整数数学的正确方法?
我真的要做到:
INT身高2 =(int)的Math.Round(
(浮动)宽度2 *((浮点)height1 /(浮点)宽度1)
);
解决方案
正如上面所说的,你应该做之前,乘法师。
反正你可以与铸造只除数写你的表达:
INT身高2 =(INT)Math.Round(宽2 *(height1 /(浮点)宽度1));
i want the result of an equation rounded to the nearest integer. e.g.
137 * (3/4) = 103
Consider the following incorrect code.
int width1 = 4;
int height1 = 3;
int width2 = 137;
int height2 = width2 * (height1 / width1);
What is the proper way to perform "integer" math in C#?
Do i really have to do:
int height2 = (int)Math.Round(
(float)width2 * ((float)height1 / (float)width1)
);
解决方案
As said above, you should do the multiplication before the division. Anyway you could write your expression with casting only the divisor:
int height2 = (int)Math.Round(width2 * (height1 / (float)width1));
这篇关于C#中:我怎样做简单的算术,舍入,对整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文