繁体   English   中英

C# - 舍入整数除法

[英]C# - Rounding the division of integers

Windows,C#,VS2010。

我的应用有这个代码:

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

如下所示,如果结果在10.0001和10.9999之间; 结果= 10

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

我需要这个:如果结果> = 10 &&结果<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)'

在此先感谢,ocaccy pontes。

尝试

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

这应该解决你的编译器错误。

第一个(“错误:以下方法或属性之间的调用不明确:'System.Math.Round(double)'和'System.Math.Round(decimal)'”)通过将被除数转换为double来解决“涓滴”使得除法的输出也是 double以避免精度损失。

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

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

(注意括号的位置)。

第二个错误(“错误:无法将类型'double'隐式转换为'int'。存在显式转换(您是否缺少转换?)”)通过显式将Math.Round的返回值转换为intMath.Round

我知道这是一个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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM