【问题标题】:C# - Rounding the division of integersC# - 舍入整数除法
【发布时间】:2013-04-23 20:59:02
【问题描述】:

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&&result=10.500&&

试试下面的代码。但没用。

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。

【问题讨论】:

  • 当您遇到错误消息时,值得运行谷歌搜索错误消息或代码 - 这通常可以为您提供解决方案。
  • 谢谢 Fabian,我真的在运行谷歌搜索并尝试解决这个问题,但我在比赛中非常慢。您的回答客观而有用。我很欣赏你的评论,谢谢。 ocaccy pontes

标签: c# math multidimensional-array int rounding


【解决方案1】:

试试

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

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

第一个(“Error: The call is ambiguous between the following methods or properties: 'System.Math.Round(double)' and 'System.Math.Round(decimal)'”)通过转换被除数解决到一个double,它会“涓涓细流”,这样除法的输出也是一个double,以避免精度损失。

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

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

(注意括号的位置)。

通过将Math.Round 的返回值显式转换为int.

【讨论】:

  • "通过将函数参数显式转换为double 来解决。" double,这使得除法发生在double 类型处,一切都很好。阅读那句话,我首先认为您将除法保留为整数除法(因此转换和舍入毫无意义)。也许重新表述一下。
  • 较短:Math.Round((myArray[x,0]+myArray[x-1,0])/(x+1.0)),无需投射
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多