C# - 舍入整数的除法

本文关键字:除法 整数 舍入 | 更新日期: 2023-09-27 18:11:31

Windows, C#, VS2010.

我的应用有以下代码:

int[,] myArray=new int[10,2];
int result=0;
int x=0;
x++;

如下所示,如果结果介于 10.0001 和 10.9999 之间;result=10

result= (myArray[x,0]+myArray[x+1,0])/(x+1); 

我需要这个:如果结果>=10&&result<10.5 舍入为 10。如果>=10.500&&<=10.999 之间的结果四舍五入为 11。

尝试以下代码。但没有奏效。

result= Math.Round((myArray[x,0]+myArray[x-1,0])/(x+1));

错误:以下方法或属性之间的调用不明确:'System.Math.Round(double(' 和 'System.Math.Round(decimal('

错误:无法将类型"double"隐式转换为"int"。存在显式转换(您是否缺少强制转换?

result= Convert.ToInt32(Math.Round((myArray[x,0]+myArray[x-1,0])/(x+1)));

错误:以下方法或属性之间的调用不明确:'System.Math.Round(double(' 和 'System.Math.Round(decimal('

提前感谢,奥卡西庞特斯。

C# - 舍入整数的除法

尝试

result= (int)Math.Round((double)(myArray[x,0]+myArray[x-1,0])/(x+1));

这应该可以消除编译器错误。

第一个("错误:调用在以下方法或属性之间不明确:"System.Math.Round(double("和"System.Math.Round(十进制("(通过将除数转换为double来解决,该"涓滴向下",使得除法的输出也是避免精度损失的double

您还可以显式将函数参数转换为double以获得相同的效果:

Math.Round((double)((myArray[x,0]+myArray[x-1,0])/(x+1)));

(请注意括号的位置(。

第二个错误("错误:无法将类型'double'隐式转换为'int'。存在显式转换(您是否缺少强制转换?通过将 Math.Round 的返回值显式转换为 int 来固定。

我知道

这是一个 3 年前的问题,但这个答案似乎很有效。 也许有人会发现这些有价值的扩展方法。

// Invalid for Dividend greater than 1073741823.
public static int FastDivideAndRoundBy(this int Dividend, int Divisor) {
    int PreQuotient = Dividend * 2 / Divisor;
    return (PreQuotient + (PreQuotient < 0 ? -1 : 1)) / 2;
}
// Probably slower since conversion from int to long and then back again.
public static int DivideAndRoundBy(this int Dividend, int Divisor) {
    long PreQuotient = (long)Dividend * 2 / Divisor;
    return (int)((PreQuotient + (PreQuotient < 0 ? -1 : 1)) / 2);
}